'How to add exactly same right axis on plotly R chart?
I have this basic script:
mtcars %>%
plot_ly() %>%
add_trace(x = ~mpg, y = ~wt, type = 'scatter', mode = 'markers' ) %>%
layout(yaxis2 = list(overlaying = "y", side = "right", title = 'test'))
It plots the chart with one axe on the left even though there is a command in layout to add a second chart.
I suppose it doesn't get triggered because nothing is plotted.
So I add the same variable
mtcars %>%
plot_ly() %>%
add_trace(x = ~mpg, y = ~wt, type = 'scatter', mode = 'markers' ) %>%
add_trace(x = ~mpg, y = ~wt, type = 'scatter', mode = 'markers', yaxis = "y2" ) %>%
layout(yaxis2 = list(overlaying = "y", side = "right", title = 'test'))
And in this case both left and right axis are the same. I suppose I could just do the second series transparent or something.
Is there a more clean solution to force the second axis to show even though nothing is plotted on it?
Solution 1:[1]
Try something like this:
library(plotly)
#Code
mtcars %>%
plot_ly() %>%
add_trace(x = ~mpg, y = ~wt, type = 'scatter', mode = 'markers' ) %>%
add_trace(x = ~mpg, y = ~wt, type = 'scatter', mode = 'markers',
yaxis = "y2") %>%
layout(yaxis2 = list(overlaying = "y", side = "right", title = 'test'))
Output:
Solution 2:[2]
Old question, but anyway:
You can't display an axis without assigning a trace to it.
However, you don't need to use the entire data again - you can simply create datapoints based on range() to achive the same an hide the trace via the opacity and showlegend parameters (using visible would prevent showing the axis):
library(plotly)
mtcars %>%
plot_ly() %>%
add_trace(x = ~mpg, y = ~wt, type = 'scatter', mode = 'markers') %>%
add_trace(x = ~range(mpg), y = ~range(wt), type = 'scatter', mode = 'markers', yaxis = "y2", opacity = 0, showlegend = FALSE) %>%
layout(showlegend = TRUE, yaxis2 = list(overlaying = "y", side = "right", title = 'test'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Duck |
| Solution 2 | ismirsehregal |


