R标绘图中的第二Y轴

anhgbhbe  于 2023-01-18  发布在  其他
关注(0)|答案(3)|浏览(141)

我合并了2个图表,并尝试添加第二个y轴,但每次我添加y轴=“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")`

任何建议都会非常有帮助。谢谢

0md85ypi

0md85ypi1#

查看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, mode = "lines", yaxis = "y2", name = "Visits") %>%
  layout(yaxis2 = list(overlaying = "y", side = "right"))

dgsult0t

dgsult0t2#

试试这个

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

e5njpo683#

在万斯洛佩斯的评论中添加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"))

相关问题