Trouble controlling axis location in R plotly subplot if multiple axes are used

Viewed 123

I'm having trouble controlling the location of axis labels and tick marks for a plotly scatter plot created with R

I read similar issues on setting layout(margin = list(pad = x)) and modifying layout(xaxis = list(domain = c(x, x2)) but the behavior is not consistent between plot and subplot, even if the subplot is simply a duplication of a plt.

The below example is illustrative of the real scenario I'm working with. I have a multi-row subplot in which the user can select up to 4 traces. The below example shows an attempt with three. You can see that the two traces anchored to "left" overlap.

  • Adjusting the pad argument to margin can separate the titles, but leaves the axis ticks and labels superimposed.
  • setting layout(yaxis(anchor = "free", position = .03)) or some other similar code causes all elements in the subplot to disappear.

I couldn't find any working examples in my search that showed a scenario with a subplot and more than 2 axes per subplot.

I'm looking for help in

  1. Fixing the below example.
  2. Better understanding of how to control the axis placement in plotly subplots. enter image description here

REPREX

plt1 <- plot_ly() %>%
  add_trace(
    data = mtcars,
    x = ~mpg,
    y = ~hp,
    name = "hp",
    yaxis = "y"
  ) %>%
  add_trace(
    data = mtcars,
    x = ~mpg,
    y = ~wt,
    name = "wt",
    yaxis = "y2"
  ) %>%
  add_trace(
    data = mtcars,
    x = ~mpg,
    y = ~drat,
    name = "drat",
    yaxis = "y3"
  ) %>%
  layout(
    showlegend = FALSE,
    yaxis = list(
      automargin = TRUE,
      side = "left",
      title = "hp"
    ),
    yaxis2 = list(
      side = "right",
      overlaying = "y",
      title = "wt"
    ),
    yaxis3 = list(
      side = "left",
      overlaying = "y",
      title = "drat"
    )
)

plt2 <- plot_ly() %>%
  add_trace(
    data = mtcars,
    x = ~mpg,
    y = ~hp,
    name = "hp",
    yaxis = "y"
  ) %>%
  add_trace(
    data = mtcars,
    x = ~mpg,
    y = ~wt,
    name = "wt",
    yaxis = "y2"
  ) %>%
  add_trace(
    data = mtcars,
    x = ~mpg,
    y = ~drat,
    name = "drat",
    yaxis = "y3"
  ) %>%
  layout(
    showlegend = FALSE,
    yaxis = list(
      side = "left",
      title = "hp"
    ),
    yaxis2 = list(
      side = "right",
      overlaying = "y2",
      title = "wt"
    ),
    yaxis3 = list(
      side = "left",
      overlaying = "y2",
      title = "drat"
    ))

subplot(plt1, plt2, shareX = TRUE, titleY = TRUE, nrows = 2) 
0 Answers
Related