【问题标题】:How to make Stacked and Grouped Barplot with ggplot2? [duplicate]如何使用 ggplot2 制作堆叠和分组条形图? [复制]
【发布时间】:2019-08-22 15:23:31
【问题描述】:

我想创建一个堆叠和分组的条形图。怎么做?

我一直在互联网上搜索,但尚未找到任何不使用分面的解决方案。

我在下面举了一个例子。

library(ggplot2)
library(reshape)

a <-data.frame(
  month=c("jan","feb","mar"),
  bread=c(1,2,3), bread_genderX=c(0,1,1), bread_genderY=c(1,1,2),
  milk=c(3,2,1),milk_genderX=c(2,0,1),milk_genderY=c(1,2,0))

# month bread bread_genderX bread_genderY milk milk_genderX milk_genderY
# jan     1             0             1    3            2            1
# feb     2             1             1    2            0            2
# mar     3             1             2    1            1            0

to_plot <- melt(a[!grepl("gender",colnames(a))], id="month")

ggplot(to_plot) +
  geom_bar(aes(x=variable,y=value, fill=month), stat = "identity",position="dodge")

此代码按 aliment 绘制分组条形图并按月填充(左图),但我想根据客户的性别将每个条分成 2 个,我没有使用的 2 个变量 genderX 和性别Y。 (右图)

如果有人知道如何做到这一点,以及我是否应该以其他方式格式化我的数据。

【问题讨论】:

    标签: r ggplot2 geom-bar stacked-chart


    【解决方案1】:

    你想要这样的东西吗?

    a <-data.frame(
      month=c("jan","feb","mar"),
      bread=c(1,2,3), bread_genderX=c(0,1,1), bread_genderY=c(1,1,2),
      milk=c(3,2,1),milk_genderX=c(2,0,1),milk_genderY=c(1,2,0))
    
    bread <- melt(cbind(a[grepl("bread",colnames(a))], month = as.factor(a$month)), id="month")
    milk <- melt(cbind(a[grepl("milk",colnames(a))], month = as.factor(a$month)), id="month")
    
    
    barwidth = 0.35
    
    ggplot() + 
      geom_bar(data = bread, 
               mapping = aes(x = variable, y = value, fill = month), 
               stat="identity", 
               position='stack', 
               width = barwidth) + 
      geom_text(data = bread, 
                aes(x = variable, y = value, label = value )) 
    

    ggplot() + 
      geom_bar(data = milk, 
               mapping = aes(x = variable, y = value, fill = month), 
               stat="identity", 
               position='stack', 
               width = barwidth) + 
      geom_text(data = milk, 
                aes(x = variable, y = value, label = value ))
    

    【讨论】:

    • 首先,感谢您的快速回答,但这并不是我想要的。我只想要一个在 x 轴上有 2 个元素(面包和牛奶)的图,每个元素有 3 个条(1 月、2 月、3 月),每个条分为 2,具体取决于男性的数量(genderY)和女性(性别X)
    猜你喜欢
    • 1970-01-01
    • 2019-01-18
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2018-03-17
    相关资源
    最近更新 更多