Creating bar plot in ggplot2 depicting count of particular value in multiple columns of dataset

Viewed 5605

I have a dataset similar to this:

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

I need to use ggplot2 to make a bar plot showing the number of "yeses" in each column. So the final bar plot would have three columns on the x-axis, with y-axis values of 4 for "Chemical," 2 for "Machinery" and 3 for "Other."

Still new to ggplot2, and also not sure how to cleanly find counts of a particular value (in this case, number of "yeses") within each column and graphing it. Thanks!

2 Answers

It's easier if you convert your data in wide format (multiple columns) to long format (fewer columns, more rows)

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

As @steveb points out, you can streamline a bit by using stat_count

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

Base-R short way to get to your graph using colSums:

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

enter image description here

Related