2
votes

In R plotly, I want to show a single line chart that has the y axis labels on BOTH the left and the right sides. I understand how to do this with 2 or more traces, but I can't find anywhere that shows how to do it with only 1 trace on the chart. Here's a basic example - it only shows the y axis on the left but I want it to appear on both sides:

library(plotly)
ay <- list(
  tickfont = list(color = "red"),
  overlaying = "y",
  side = "right",
  title = "second y axis"
)
fig <- plot_ly()
fig <- fig %>% add_lines(x = ~1:3, y = ~10*(1:3), name = "slope of 10")
fig <- fig %>% layout(
  title = "Double Y Axis", yaxis2 = ay,
  xaxis = list(title="x")
)

fig
1
this is it! the addition of transparency and turning off hoverinfo does itJoe

1 Answers

1
votes

You can add the same values in a new axis like this:

library(plotly)
#Setup
ay <- list(
  tickfont = list(color = "red"),
  overlaying = "y",
  side = "right",
  title = "second y axis"
)
#Plot
fig <- plot_ly()
fig <- fig %>% add_lines(x = ~1:3, y = ~10*(1:3), name = "slope of 10", yaxis = "y2")
fig <- fig %>% 
  add_lines(x = ~1:3, y = ~10*(1:3), name = "slope of 10") %>%
  layout(
  title = "Double Y Axis", yaxis2 = ay,
  xaxis = list(title="x")
)

Output:

enter image description here

If you want to remove the legend:

#Plot 2
fig <- plot_ly()
fig <- fig %>% add_lines(x = ~1:3, y = ~10*(1:3), name = "slope of 10", yaxis = "y2")
fig <- fig %>% 
  add_lines(x = ~1:3, y = ~10*(1:3), name = "slope of 10") %>%
  layout(
  title = "Double Y Axis", yaxis2 = ay,
  xaxis = list(title="x"),showlegend = FALSE
)

Output:

enter image description here