我合并了2个图表,我试图添加第二个y轴,但每次添加yaxis =" y2"在我的代码中,我失去了我的条形图。
> MediaDate Spend Search_Visits Other_Visits MediaDate2
> 2016-04-01 $39654.36 19970 2899 Apr 2016
> 2016-05-01 $34446.28 14460 2658 May 2016
> 2016-06-01 $27402.36 12419 2608 Jun 2016
我的原始代码是:
p <- plot_ly(x= w$MediaDate2,y=w$Search_Visits,name = "Paid Search",
type = "bar")
p2 <- add_trace(p, x=w$MediaDate2, y=w$Other_Visits,name = "Other Traffic",
type = "bar")
spend_visits <- layout(p2, barmode = "stack")
spendvisits2 <- spend_visits %>% add_trace(data=w, x=MediaDate2, y=round(Spend,0), fill="tonexty", mode="lines",
text=w$MediaDate2, hoverinfo='name+y+text', name="Spend")
当我添加yaxis =&#34; y2&#34;时,只剩下面积图:
`spendvisits2 <- spend_visits %>% add_trace(data=w, x=MediaDate2, y=round(Spend,0), yxis="y2" fill="tonexty", mode="lines",
text=w$MediaDate2, hoverinfo='name+y+text', name="Spend")`
任何建议都会非常有帮助。谢谢
答案 0 :(得分:6)
对于多个轴,请参阅此快速Plotly tutorial。您需要在layout()
中指定第二个y轴的属性。
df <- data.frame(MediaDate = as.Date(c("2016-04-01","2016-05-01","2016-06-01"), format = "%Y-%m-%d"),
Spend = c(39654, 34446, 27402),
Visits = c(19970, 14450, 12419))
plot_ly(df, x = MediaDate, y = Spend, type = "bar", name = "Spend") %>%
add_trace(x = MediaDate, y = Visits, modee = "lines", yaxis = "y2", name = "Visits") %>%
layout(yaxis2 = list(overlaying = "y", side = "right"))
答案 1 :(得分:1)
试试这个
plot_ly(df) %>%
add_trace(x = ~MediaDate, y = ~Spend,type = "bar", name = "Spend") %>%
add_trace(x = ~MediaDate, y = ~Visits, mode = "lines", yaxis = "y2", name = "Visits") %>%
layout(yaxis2 = list(overlaying = "y", side = "right"))