【问题标题】:Creating bar plot in ggplot2 depicting count of particular value in multiple columns of dataset在 ggplot2 中创建条形图,描述数据集中多列中特定值的计数
【发布时间】:2017-09-22 16:18:04
【问题描述】:

我有一个类似这样的数据集:

Area             Chemical   Machinery   Other
Abilene TX       Yes        No          Yes
Akron OH         Yes        No          No
Albany GA        Yes        Yes         No
Albuquerque NM   No         Yes         Yes
Alexandria LA    Yes        No          Yes

我需要使用 ggplot2 制作一个 条形图,显示每列中“yes”的数量。所以最终的条形图将在 x 轴上有三列,y 轴值为 4 表示“化学”,2 表示“机械”,3 表示“其他”。

仍然是 ggplot2 的新手,也不确定如何在每列中干净地找到特定值的计数(在本例中为“yes”的数量)并绘制图表。谢谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    如果您将宽格式(多列)的数据转换为长格式(更少的列,更多的行)会更容易

    library(tidyr)
    library(dplyr)
    yes <- df %>%
      select(-Area) %>%
      gather() %>%
      group_by(key) %>%
      summarise(value = sum(value=="Yes"))
    
    # A tibble: 3 x 2
            # key value
          # <chr> <int>
    # 1  Chemical     4
    # 2 Machinery     2
    # 3     Other     3
    
    library(ggplot2)
    ggplot(yes, aes(x=key, y=value)) + 
      geom_bar(stat="identity")
    

    正如@steveb 指出的那样,您可以通过使用stat_count 来简化一点

    df %>% 
      select(-Area) %>% 
      gather() %>% 
      filter(value == 'Yes') %>% 
      ggplot(aes(key, ..count..)) + geom_bar()
    

    【讨论】:

    • 如果您使用geom_bar()(即没有stat = "identity"),您也可以避免使用group_bysummarise。您当然会过滤“是”行。例如:df %&gt;% select(-Area) %&gt;% gather() %&gt;% filter(value == 'Yes') %&gt;% ggplot(aes(key,..count..)) + geom_bar()
    • 不错。 geom_bar(stat="identity") 可以替换为geom_col(),可以说与使用..count.. 一样精简
    【解决方案2】:

    使用 colSums 获取图表的 Base-R 快捷方式:

    n_yes <- data.frame(type = names(df[, -1]), 
                        total_yes = colSums(df[, -1] == "Yes"))
    
    ggplot(n_yes, aes(x = type, y = total_yes)) + 
      geom_bar(stat = "identity")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 2021-07-17
      • 2019-03-20
      • 2022-01-18
      • 2020-05-06
      • 1970-01-01
      相关资源
      最近更新 更多