【问题标题】:How to create stack bar chart using ggplot [duplicate]如何使用ggplot创建堆栈条形图[重复]
【发布时间】:2018-03-20 15:53:41
【问题描述】:

我有一个数据集如下:

A   B   C
1   1   1
0   1   1
1   0   1
1   0   1

我想要一个堆栈条形图,在一个图中显示每列中 1 和 0 的百分比,紧挨着其他列。

【问题讨论】:

  • 请展示您到目前为止尝试过的内容以及遇到问题的地方。

标签: r ggplot2


【解决方案1】:

您需要采取几个步骤:

  • 计算每个变量有多少个零和一
  • 计算相对百分比(你没有在你的问题中定义这个
  • 重排数据从宽到长(使用tidyr::gather
  • 使用ggplotgeom_bar 绘图

【讨论】:

    【解决方案2】:

    首先你需要整理你的数据

    library(tidyr)
    
    A = c(1,0,1,1)
    B = c(1,1,0,0)
    C = c(1,1,1,1)
    
    data = data.frame(A,B,C)
    data = gather(data, key = type, value = val)
    

    然后计算你的统计数据

    library(dplyr)
    perc = group_by(data, type) %>% summarise(perc = sum(val)/length(val))
    

    完成绘制它们

    library(ggplot2)
    ggplot(perc) + aes(x = type, y = perc) + geom_bar(stat = "identity")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 2021-11-13
      相关资源
      最近更新 更多