R plotly图表中的第二个Y轴

9

我合并了两个图表,现在想要添加第二个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="y2"时,只有面积图保留:
`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")` 

任何建议都将非常有帮助。谢谢。
3个回答

20

查看此快速Plotly多轴教程。您需要在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, mode = "lines", yaxis = "y2", name = "Visits") %>%
  layout(yaxis2 = list(overlaying = "y", side = "right"))

在此输入图片描述


谢谢,代码完美运行!我知道要创建一个面积图,需要添加代码[fill="tozeroy"]。但是是否有一种方法可以将条形图与区域图重叠? - Nisha G.
1
“'bar'对象没有这些属性:'mode'”我遇到了这个错误。 - Nabi Shaikh
2
可能有一种解决方案可以生成我认为 OP 所询问的分组条形图吗? - Pake

3

试试这个

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"))

0

在 Vance Lopez 评论的代码中添加 type='scatter' 对我有效:

plot_ly(df, x = ~MediaDate, y = ~Spend, type = "bar", name = "Spend") %>%
    add_trace(x = ~MediaDate, y = ~Visits, type = 'scatter', mode = "lines", yaxis = "y2", name = "Visits") %>%
    layout(yaxis2 = list(overlaying = "y", side = "right"))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接