简体   繁体   English

R plotly 图中的第二个 Y 轴

[英]Second Y-Axis in a R plotly graph

I combined 2 charts and I am trying to add the second y-axis, but every time I add the yaxis = "y2" to my code, I lose have the my bar graphs.我组合了 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

my original code is:我的原始代码是:

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

When I add the yaxis= "y2", only the area chart remains:当我添加 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")` 

Any suggestions would be immensely helpful.任何建议都会非常有帮助。 Thank you谢谢

See this quick Plotly tutorial for multiple axes.有关多轴的信息,请参阅此快速Plotly 教程 You need to specify the attributes for the second y axis in layout() .您需要在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"))

在此处输入图片说明

Try this尝试这个

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

Adding type='scatter' to what Vance Lopez commented worked for me:将 type='scatter' 添加到 Vance Lopez 评论的内容中对我有用:

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")) plot_ly(df, x = ~MediaDate, y = ~Spend, type = "bar", name = "Spend") %>% add_trace(x = ~MediaDate, y = ~Visits, type = 'scatter', 模式 = " lines”, yaxis = “y2”, name = “Visits”) %>% layout(yaxis2 = list(overlaying = “y”, side = “right”))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM