首页 文章

R在条形图上绘制多个尺寸

提问于
浏览
0

我必须用下面的数据创建一个堆积条形图

df <- data.frame(
  var1 = c("NY", "NY", "NY", "SFO", "SFO", "SFO"),
  var2 =  c("LOW", "Medium", "High", "Low", "Medium", "High"),
  value = c(10, 15, 20, 15, 20, 15)
)

基本上,x轴将具有2个用于var1的条形,填充每个var2的值 . 在ggplot中你可以使用var2作为填充但我无法弄清楚如何在plotly中执行此操作 .

有人可以帮忙吗?

谢谢,

马诺

1 回答

  • 0

    你可以试试:

    # Split the data
    df_list <- split(df, df$var2)
    # plot the data and add the traces for var2
    plot_ly(df_list$Low, x=~var1, y=~value, type="bar", name="Low") %>%
      add_trace(y= df_list$Medium$value , name = "Medium") %>%
      add_trace(y= df_list$High$value, name = "High") %>%
      layout(barmode = "stack")
    

    enter image description here

    # A faster way would be something like this:
    # First order var2
    df$var2 <- factor(df$var2,levels = c("Low", "Medium", "High"))
    # Plot 
    plot_ly(df, x= ~var11, y= ~value, color= ~var2, type="bar") %>% layout(barmode = "stack")
    

    后期解决方案未正确显示图例中的颜色,这似乎是情节版本 plotly_4.5.2 中的错误 . 在xaxis上绘制两个以上的条形图是没有任何问题的 . 使用三个 var1 组尝试此数据:

    df2 <- data.frame(
      var1 = c("NY", "NY", "NY", "SFO", "SFO", "SFO","Test"),
      var2 =  c("Low", "Medium", "High", "Low", "Medium", "High","Low"),
      value = c(10, 15, 20, 15, 20, 15,30)
    )
    plot_ly(df2, x=~var1, y=~value, color=~var2, type="bar") %>% layout(barmode = "stack")
    
    # Or use ggplot
    library(ggplot2)
    p <- ggplot(df, aes(x=var1, y=value, fill=var2)) + geom_bar(stat="identity") + theme_bw()
    ggplotly(p)
    

    enter image description here

相关问题