r - 在 ggplot2 中创建条形图,描述数据集多列中特定值的计数

标签 r ggplot2

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

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 制作一个条形图,显示每列中"is"的数量。因此,最终的条形图将在 x 轴上具有三列,y 轴值为 4 表示“化学”,2 表示“机械”,3 表示“其他”。

对 ggplot2 还是个新手,也不确定如何在每一列中清楚地找到特定值的计数(在本例中为"is"的数量)并绘制它。谢谢!

最佳答案

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

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()

关于r - 在 ggplot2 中创建条形图,描述数据集多列中特定值的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46355263/

相关文章:

rowDiffs 类型函数,保留 "row 1"作为每组的引用行

R ggplot 方面 : varying x axis formatting and varying aesthetics by facet

r - 如何编写dplyr组以分隔文件?

r - 如何在 valueBox shinydashboard 中格式化货币值?

r - 如何修改 Shiny 应用程序中的绘图大小?

r - 在ggplot中绘制平滑正态分布的最佳方法

r - 在 ggplot2 中强制 y 轴为 100%

r - ggplot r 中热图标签中的上标

具有发散调色板的 R 热图

r - 当数据中不存在分组变量的所有级别时,图之间的色标和图例一致