1
votes

I'm trying to create a plot in R with plotly (v. 4.9.2.1) with three panels sharing an x-axis, the last of which shows two variables with the second on a separate y-axis. I made a toy example below with fake data that reproduces the basic problem I'm having. The issue is that as soon as I include a second y-axis I cannot get the x-axis title to correctly appear at the bottom of all the plots. In the code below I specifically enter the xaxis argument for all the traces, though removing that doesn't make any difference. Also, placing the x title in the layout of the other plots doesn't change anything, either, and the margin in the final plot is to ensure the y-axis tick labels are visible and doesn't change the axis label placement.

set.seed(123)
x1 <- seq(from=1, to=100, by=5)
x2 <- seq(from=1, to=100, by=3)
x3 <- seq(from=1, to=100, by=2)
x4 <- c(1,23,50,80)

y1 <- rnorm(length(x1))
y2 <- rnorm(length(x2))
y3 <- rnorm(length(x3))
y4 <- c(0,10,0,10)

p1 <- plot_ly(showlegend=FALSE) %>%
  add_markers(x=x1, y=y1, xaxis='x')

p2 <- plot_ly(showlegend=FALSE) %>%
  add_markers(x=x2, y=y2, xaxis='x')

p3 <- plot_ly(showlegend=FALSE) %>%
  add_markers(x=x3, y=y3, yaxis='y3', xaxis='x') %>%
  add_lines(x=x4, y=y4, line=list(shape='hv'), yaxis='y4', xaxis='x') %>%
  layout(yaxis3=list(overlaying='y4'),
         yaxis4=list(side='right'),
         margin=list(r=50))

subplot(p1, p2, p3, nrows = 3, shareX=TRUE) %>% layout(xaxis=list(title='Time'))

enter image description here

1

1 Answers

1
votes

The xaxis is by default anchored to the default "yaxis". In your case it is the one on top.

To get the xaxis to be placed at the bottom, you can modify its anchor to another yaxis: "y2" for the middle subplot, "y3" or "y4" for the bottom subplot.

To do so, specify the anchor attribute of the xaxis when you add the layout:

layout(xaxis=list(title='Time', anchor="y3"))

NB: To check your code and see how your axis are anchored to each other, you can print the full structure of your plotly figure in a json format:

fig <- subplot(p1, p2, p3, nrows = 3, shareX=TRUE)
fig <- layout(fig, xaxis=list(title='Time', anchor="y3"))
plotly_json(fig) 

And you will be able to check:

 "layout": {
    "xaxis": {
      "domain": [0, 1],
      "automargin": true,
      "title": "Time",
      "anchor": "yaxis2"
    },
    "yaxis3": {
      "overlaying": "y4",
      "anchor": "x",
      "domain": [0, 0.313333333333333]
    },
...