R:双 Y 轴绘图?

R: plotly graph with dual Y axis?

我找到了这个问题,但答案不是最新的,无法产生正确的结果。

如何绘制双 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"))

产生:

我需要什么(但不是一个条和一条线,而是 2 条线):

这是一种方法:

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

old.y <- list(
  side = "left",
  title = "Spend"
)

new.y <- list(
  overlaying = "y",
  side = "right",
  title = "Visits"
)

plot_ly(df) %>%
  add_lines(x = ~MediaDate, y = ~Spend, yaxis="y1") %>%
  add_lines(x = ~MediaDate, y = ~Visits, yaxis = "y2") %>%
  layout(yaxis2 = new.y, yaxis = old.y, xaxis = list(title="MediaDate"))