1
votes

I am trying to create a plotly graph with two y-axes, one on the left-hand side and one on the right-hand side of the plot. I got the following (reproducible example) code working:

library(dplyr)
library(plotly)

plot_ly() %>% 
  add_lines(x = ~1:3, y = ~10*(1:3), name = "slope of 10") %>% 
  add_lines(x = ~2:4, y = ~1:3, name = "slope of 1", yaxis = "y2") %>% 
  layout(
    title = "Double Y Axis", 
    yaxis2 =  list(tickfont = list(color = "red"),
                   overlaying = "y",
                   side = "right",
                   title = "second y axis"),
    xaxis = list(title="x")
  )

However, with my actual data, the legend is somewhat weirdly positioned and overlaps with the y-axis tick labels and the title. As it is reactive data, I don't know for every situation what the y-axes will look like. Therefore, I would like to move the legend to the bottom (horizontally oriented) to give the y-axis more space. Although I have the code to move the legend (see the code chunck below), it resulted in a rescaling of the graph that made the secondary Y-axis unreadable. As you can see in the example picture the decimals aren't in the graph area anymore and the y-axis title now overlaps with the tick labels.

plot_ly() %>% 
  add_lines(x = ~1:3, y = ~10*(1:3), name = "slope of 10") %>% 
  add_lines(x = ~2:4, y = ~1:3, name = "slope of 1", yaxis = "y2") %>% 
  layout(
    title = "Double Y Axis", 
    yaxis2 =  list(tickfont = list(color = "red"),
                   overlaying = "y",
                   side = "right",
                   title = "second y axis"),
    xaxis = list(title="x"),
    legend = list(orientation = 'h', x = 0.35, y = -.15)
  )

Example plot

Is it possible to rescale the plot so it becomes readable? I tried adjusting the position of the secondary y-axis, but that also resulted in a ugly result (as the axis will be somewhere in the 'middle' of your plot). So my prefered outcome is the y-axis and its title similarly positioned as in the first code example, with the legend (horizontally oriented) at the bottom of the plot as in the second code example.

1

1 Answers

1
votes

You can add a margin (currently only increase the margin on the right for "r") to the plot as the title is anchor to the right side.

plot_ly() %>% 
  add_lines(x = ~1:3, y = ~10*(1:3), name = "slope of 10") %>% 
  add_lines(x = ~2:4, y = ~1:3, name = "slope of 1", yaxis = "y2") %>% 
  layout(
    title = "Double Y Axis", 
    yaxis2 =  list(tickfont = list(color = "red"),
                   overlaying = "y",
                   side = "right",
                   title = "second y axis"
                   ),
    xaxis = list(title="x"),
    margin = list(
          r = 50
    ),
    legend = list(orientation = 'h', x = 0.35, y = -.15)
  ) 
  

Example