R图形图中的第二个Y轴

Nis*_* G. 3 r graph axis-labels plotly

我合并了两个图表,我试图添加第二个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
Run Code Online (Sandbox Code Playgroud)

我原来的代码是:

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") 
Run Code Online (Sandbox Code Playgroud)

当我添加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")` 
Run Code Online (Sandbox Code Playgroud)

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

Van*_*pez 7

请参阅此快速Plotly教程了解多个轴.您需要指定第二个y轴的属性layout().

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"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 是否有一种解决方案可以生成我认为 op 所要求的分组条形? (2认同)