Reputation: 153
I want to have two subplots, same x-axis. In the top plot, I want to have two y-axes. If I only show top
, both plots are correctly displayed. But in both
, the plot from df2 is missing. Why and how can I fix it?
library(plotly)
library(tidyverse)
df1 <- data.frame(t=seq(5)) %>% mutate(d1=t+7)
df2 <- data.frame(t=seq(2,6)) %>% mutate(d2=t*t+20)
df3 <- data.frame(t=seq(0,8)) %>% mutate(d3=-2-t)
top <- plot_ly() %>%
add_trace(x=~t,y=~d1,type="scatter",data=df1,mode="lines") %>%
add_trace(x=~t,y=~d2,type="scatter",data=df2,mode="lines",yaxis = "y2") %>%
layout(yaxis2 = list(overlaying = "y", side = "right"))
bottom <- plot_ly() %>%
add_trace(x=~t,y=~d3,type="scatter",data=df3,mode="lines")
both <- list(top ,bottom ) %>% subplot(nrows=2,shareX=T)
I tried to understand a similar question asked for Python, but I don't see how it relates to my code.
Upvotes: 2
Views: 66
Reputation: 41225
For the plot with dual axis you should change the layout
of yaxis
to left side which is your first axis, yaxis2 to right as second yaxis and with the "overlaying" argument to "y". Here is a reproducible example:
library(plotly)
library(dplyr)
df1 <- data.frame(t=seq(5)) %>% mutate(d1=t+7)
df2 <- data.frame(t=seq(2,6)) %>% mutate(d2=t*t+20)
df3 <- data.frame(t=seq(0,8)) %>% mutate(d3=-2-t)
top <- plot_ly() %>%
add_trace(x=~t,y=~d1,type="scatter",data=df1,mode="lines") %>%
add_trace(x=~t,y=~d2,type="scatter",data=df2,mode="lines",yaxis = "y2") %>%
layout(yaxis=list(side="left"),
yaxis2=list(side="right",overlaying="y"))
bottom <- plot_ly() %>%
add_trace(x=~t,y=~d3,type="scatter",data=df3,mode="lines")
subplot(top, bottom, nrows = 2, shareX = TRUE)
Created on 2023-01-17 with reprex v2.0.2
Upvotes: 2