【问题标题】:Summarise and create a stacked bar chart in R在 R 中总结并创建堆积条形图
【发布时间】:2023-03-17 15:43:02
【问题描述】:

对于一群人,我有一个关于他们所属类别的定期时间序列。我想按照 R 中的堆积条形图,按类别总结这个人口的组成。例如:

set.seed(1)
id <- seq(1:25)
t1 <- sample(LETTERS[1:5], 25, replace=TRUE)
t2 <- sample(LETTERS[1:5], 25, replace=TRUE, prob=c(0.1,0.1,0.1,0.1,0.6))
t3 <- sample(LETTERS[1:5], 25, replace=TRUE, prob=c(0.2,0.1,0.2,0.1,0.4))

df <- data.frame(cbind(id, t1, t2, t3))

有频率:

> table(df$t1)

A B C D E 
7 6 3 2 7 
> table(df$t2)

 B  C  D  E 
 3  4  5 13 
> table(df$t3)

 A  B  C  D  E 
 4  2  5  4 10 

因此,在时间段 1,25 个中有 7 个是 A 类,6 个是 B 类,而在时间段 2,没有一个是 A 类,3 个是 B 类,等等。图表将如下所示(来自 EXCEL):


这可以用ggplot制作吗?谢谢。

【问题讨论】:

    标签: r ggplot2 stacked-chart


    【解决方案1】:

    这是data.table的选项

    library(dplyr)
    library(data.table)
    library(ggplot2)
    
    melt(setDT(df), id.var = "id")[, .N, .(variable, value)][, perc := N / sum(N), variable] %>%
      ggplot(aes(x = variable, y = perc, fill = value)) +
      geom_bar(stat = "identity") +
      scale_y_continuous(labels = scales::percent)
    

    【讨论】:

    • 感谢您的选择。我应该说实际上我有将近 350,000 行。这个解决方案似乎是最快的。
    【解决方案2】:

    这可以通过首先使用pivot_longer 重塑为“长”格式,然后获取频率count 并在ggplot aes 中使用汇总的“n”作为“y”,同时指定“x” ' 作为 'name' 和 fill 作为从 pivot_longer 创建的 'value' 列

    library(dplyr)
    library(tidyr)
    library(ggplot2)
    df %>%
        pivot_longer(cols = everything()) %>% 
        count(name, value) %>% 
        ggplot(aes(x = name, y = n, fill = value)) +
            geom_col()
    

    如果我们需要比例而不是计数,

    df %>%
          pivot_longer(cols = everything()) %>% 
          count(name, value) %>%
          group_by(name) %>%
          mutate(prop =  n/sum(n)) %>% 
          ggplot(aes(x = name, y = prop, fill = value)) + 
             geom_col() +
             scale_y_continuous(labels= scales::percent)
    

    【讨论】:

      猜你喜欢
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      相关资源
      最近更新 更多