带折线图的堆积条形图在 R 中无法使用 plotly [英] Stacked Bar Chart with Line Chart not working in R with plotly

查看:73
本文介绍了带折线图的堆积条形图在 R 中无法使用 plotly的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying top prepare stacked bar chart with line chart and two y axis in R using plotly, but line part is not displaying. Both y axis are fine, stacked bar chart also works. Line chart by itself also works, but not together with stacked bar chart. When I tried it with only one y axis chart had all components, but because of different scale it's not visualizing data well enough. Here is code with sample data:

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

知道如何纠正它吗?

推荐答案

这对我有用:

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

这篇关于带折线图的堆积条形图在 R 中无法使用 plotly的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆