Search code examples
rggplot2plotlyggplotly

Double-Y axis plots over ggplot generated figures using plotly


I just started using plotly and am having issues getting doubly-y axis plots to work. I generated my initial figure in ggplot with two, but only one appears when I run it through ggplotly(). I have been unable to figure out how to add one with layout().

I created a double-y axis plot in ggplot, but when I plotted it with ggplotly it dropped the second y axis. I then tried to use the technique on their website (https://plotly.com/r/multiple-axes/), defining a second label then attaching it with layout(). It modifies the labels present, but does not add the second y axis. Any advice on how I might operationalize this? code example below.

Thanks!

#packages
library(tidyverse)
library(plotly)

#Create functional double-y plot
dbly<-mtcars %>% ggplot(aes(x = disp)) + 
  geom_point(aes(y = hp), color = "red")+
  geom_point(aes(y = mpg * 9), color = "blue")+ 
scale_y_continuous(name = "hp", sec.axis = sec_axis(~ . /9, name = "mpg"))

dbly

#Double-y plot loads both datasets but not both axes
egads<-ggplotly(dbly)
egads

#attempted to apply layout - second y axis, overwrites other 
#labels but does not add second y
ay <- list(
  tickfont = list(color = "red"),
  overlaying = "y",
  side = "right",
  title = "<b>secondary</b> yaxis title")

egads%>% layout(
  title = "Double Y Axis Example", yaxis2 = ay,
  xaxis = list(title="xaxis title "),
  yaxis = list(title="<b>primary</b> yaxis title")
)


Solution

  • Here is a how we could do it: Credits to

    library(plotly)
    
    # defining the attributes for the second y axis:
    ay <- list(
      tickfont = list(color = "red"),
      overlaying = "y",
      side = "right",
      title = "hp"
    )
    
    
    plot_ly(mtcars, x = ~disp, y = ~hp, type = "scatter", mode = "markers", name='hp') %>% 
      add_trace(y = ~mpg, name = 'mpg', yaxis = "y2") %>% 
    layout(title = 'hp and mpg distribution', 
           yaxis = list(title = 'mpg'), 
           xaxis= list(title="disp"), 
           yaxis2 = ay)
    
    

    enter image description here