0

Since ggplotly does not supportggplot2's sec.axis (Adding second Y axis on ggplotly), I want to add a second axis to the plotly-object instead. However, I do not wish to add any new trace.

Example:

library(plotly)
ay <- list(
  tickfont = list(color = "red"),
  overlaying = "y",
  side = "right",
  title = "second y axis"
)
p <- 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 = ay,
    xaxis = list(title="x")
  )

p

How do I accomplish showing yaxis = "y2" without add_lines or adding any other trace?

enter image description here

Comfort Eagle
  • 2,112
  • 2
  • 22
  • 44

1 Answers1

1

One way to achieve this is to do what you have done and change the color of whatever you add for the second axis to "transparent", and turn off the hoverinfo and legend entry for the line :

library(plotly)
ay <- list(
  tickfont = list(color = "red"),
  overlaying = "y",
  side = "right",
  title = "second y axis"
)
p <- plot_ly() %>%
  add_lines(x = ~1:3, y = ~10*(1:3), name = "slope of 10") %>%
  add_lines(x = ~2:4, y = ~1:3, color = I("transparent"), name = "", yaxis = "y2", hoverinfo='skip', showlegend=FALSE) %>%
  layout(
    title = "Double Y Axis", yaxis2 = ay,
    xaxis = list(title="x")
  )
p

enter image description here

Community
  • 1
  • 1
Zhiqiang Wang
  • 6,206
  • 2
  • 13
  • 27