带有折线图的堆积条形图在R中无法使用情节

时间:2016-07-14 10:04:10

标签: r plotly

我正在尝试顶部准备堆积条形图与折线图和两个y轴在R中使用plotly,但线部分不显示。两个y轴都很好,堆叠条形图也可以。折线图本身也有效,但不能与堆积条形图一起使用。当我尝试它只有一个y轴图表有所有组件,但由于不同的规模,它不能很好地可视化数据。以下是包含示例数据的代码:

library(plotly)

#data
big <- c(300000,400000,500000,600000,500000,600000)
v1 <- c(3,4,5,5,4,3)
v2 <-c(3,4,5,5,4,3)
Date <- c("Jan 2016","Feb 2016","Mar 2016","Apr 2016","May 2016","June 2016")
df <- data.frame(big, v1, v2, Date)

#plot
p1 <- plot_ly(
   x = df$Date,
   y = df$big,
   type="scatter"
)

p2 <- add_trace(
   p1,
   x = df$Date,
   y = df$v2,
   type = "bar",
   yaxis="y2")

p25 <- add_trace(
   p2,
   x = df$Date,
   y = df$v1,
   type = "bar",
   yaxis="y2"
)

p3 <- layout(p25, 
             xaxis = list(
                title = "Month"
             ),
             yaxis = list(
                title = "big"
             ),
             yaxis2=list(
                title = "little",
                tickfont = list(color = "red"),
                overlying="y",
                side="right"
             ),
             barmode="stack"
)

p3

知道如何纠正它吗?

1 个答案:

答案 0 :(得分:0)

这对我有用:

# data
big <- c(300000,400000,500000,600000,500000,600000)
v1 <- c(3,4,5,5,4,3)
v2 <-c(3,4,5,5,4,3)
Date <- c("Jan 2016","Feb 2016","Mar 2016","Apr 2016","May 2016","June 2016")
df <- data.frame(big, v1, v2, Date)

library(plotly)

df %>% 
  plot_ly(x = ~Date) %>% 
  add_bars(y = ~v1,
           name = "bar1") %>% 
  add_bars(y = ~v2,
           name = "bar2") %>%
  add_lines(y = ~big,
            name = "line",
            yaxis = "y2") %>% 
  layout(barmode = "stack",
         yaxis2 = list(overlaying = "y",
                       side = "right"),
         barmode = "stack")

enter image description here