R: subplot with plots that have multiple y-axis and x-axis

Viewed 174

I am trying to draw a subplot that contains 2 plots. Each inner plots have two y-axis and two x-axis. I also want to match each y label with his lines color.

First I want to start with a simple example. Consider following code

 library(plotly)
 library(dplyr)
 p1 <- economics %>% plot_ly()%>%
   add_trace( x = ~date, y = ~unemploy,yaxis='y1',type='scatter',mode="lines+markers")%>%
   add_trace(x = ~date, y = ~uempmed,yaxis='y2',type='scatter',mode="lines+markers") %>% 
   layout( yaxis2 =  list(overlaying = "y1",side = "right"))
  p2<-p1
  >p1

The output:

enter image description here

  subplot(p1, p2 , nrows = 2 , shareX = TRUE)

The output:

enter image description here

So the subplot does not work fine. How to fix it?

EDIT:

With a little change to the code as shown below and it work!

enter image description here

   R code
 library(plotly)
 library(dplyr)
 p1 <- economics %>% plot_ly()%>%
   add_trace( x = ~date, y =~unemploy,yaxis='y',type='scatter',mode="lines+markers")%>%
   add_trace(x = ~date, y = ~uempmed,yaxis='y2',type='scatter',mode="lines+markers") %>% 
   layout( yaxis =  list(side = "left"),yaxis2 =  list(overlaying = "y",side = "right"))
  p2<-economics %>% plot_ly()%>%
   add_trace( x = ~date, y = ~unemploy,yaxis='y',type='scatter',mode="lines+markers")%>%
   add_trace(x = ~date, y = ~uempmed,yaxis='y2',type='scatter',mode="lines+markers") %>% 
   layout(yaxis =  list(side = "left"), yaxis2 =  list(overlaying = "y3",side = "right"))
subplot(p1,p2,nrows=2)

The output now is as follows:

enter image description here

To extend for have 3 plots:

enter image description here

 library(plotly)
 library(dplyr)
 p1 <- economics %>% plot_ly()%>%
   add_trace( x = ~date, y = ~unemploy,yaxis='y',type='scatter',mode="lines+markers")%>%
   add_trace(x = ~date, y = ~uempmed,yaxis='y2',type='scatter',mode="lines+markers") %>% 
   layout( yaxis =  list(side = "left"),yaxis2 =  list(overlaying = "y",side = "right"))
  p2<-economics %>% plot_ly()%>%
   add_trace( x = ~date, y = ~unemploy,yaxis='y',type='scatter',mode="lines+markers")%>%
   add_trace(x = ~date, y = ~uempmed,yaxis='y2',type='scatter',mode="lines+markers") %>% 
   layout(yaxis =  list(side = "left"), yaxis2 =  list(overlaying = "y3",side = "right"))
p3<-economics %>% plot_ly()%>%
   add_trace( x = ~date, y = ~unemploy,yaxis='y',type='scatter',mode="lines+markers")%>%
   add_trace(x = ~date, y = ~uempmed,yaxis='y2',type='scatter',mode="lines+markers") %>% 
   layout(yaxis =  list(side = "left"), yaxis2 =  list(overlaying = "y5",side = "right"))

subplot(p1,p2,p3,nrows=3)

The output:

enter image description here

0 Answers
Related