3

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 2

3

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()
Sign up to request clarification or add additional context in comments.

2 Comments

You can also avoid the group_by and summarise if you use geom_bar() (i.e. without the stat = "identity". You would of course filter on 'Yes' rows. Example: df %>% select(-Area) %>% gather() %>% filter(value == 'Yes') %>% ggplot(aes(key,..count..)) + geom_bar()
Nice. geom_bar(stat="identity") can be replaced by geom_col(), which is arguably just as streamlined as using ..count..
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.