Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot with multiples axes

Tags:

plot

r

plotly

I've created a plot in R that has multiple y axes on the same side. However the additional axes overlay the plot, and when the graph is more noisy it causes the issue.

This is what I have:

enter image description here

While what I need is something like this:

enter image description here

Sample code:

library(plotly)
ay <- list(
  tickfont = list(color = "red"),
  overlaying = "y",
  side = "left",
  title = "second y axis",
  position = 0.1
)
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
like image 785
Galina Polishchuk Avatar asked Sep 17 '26 16:09

Galina Polishchuk


1 Answers

To my knowledge, multiple y axes are not correctly managed in plotly for R and the only trick available to circumvent the above problem is to tune margin attributes, as proposed here.

library(plotly)
ay <- list(
  tickfont = list(color = "red"),
  overlaying = "y",
  side = "left",
  title = "second y axis",
  anchor="free"
)

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"), 
    yaxis = list(showline = FALSE, side="left"),
    margin=list(pad = 50, b = 90, l = 150, r = 90)
  )   
p

enter image description here

like image 85
Marco Sandri Avatar answered Sep 20 '26 10:09

Marco Sandri