0

I've used this code:

data %>% 
gather(activity, ct, ActSwim:acteat) %>% 
filter(ct == 1) %>% 
count(activity, Location) %>% 
ggplot(., aes(activity, n)) +
geom_barplot(stat = "identity") + 
facet_wrap(~Location, ncol = 1)

to create thisenter image description here

How can I change this from counts to proportions to account for the fact that differing numbers of people were surveyed at each location? I want the proportions to reflect the proportion of each facet (in this case location).

1 Answers1

0

Despite the fact that this may be a duplicate, you've two options.

  1. Make ggplot do the conversions for you.
  2. Summarize your data yourself and pass it to ggplot

I subscribe to #2, as it offers a lot more flexibility in the long run.

library(dplyr)
library(ggplot2)
library(scales)

data %>% 
  gather(activity, ct, ActSwim:acteat) %>% 
  filter(ct == 1) %>% 
  count(activity, Location) %>% 
  group_by(activity) %>%
  mutate(percentage = n/sum(n)) %>%
  ggplot(., aes(activity, percent)) +
  geom_col() + 
  facet_wrap(~Location, ncol = 1) +
  scale_y_continuous(labels = percent)
Jake Kaupp
  • 7,892
  • 2
  • 26
  • 36
  • I tried using this code but I'm getting "Error in data.frame(x = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, : arguments imply differing number of rows: 33, 0". – Chelsea Acres Dec 06 '16 at 15:25
  • To be clear, I want the final graph to show proportions within each facet. So this question is not a duplicate of what's been linked. – Chelsea Acres Dec 06 '16 at 16:51
  • Realized I used `summarize` instead of `mutate` hopefully that will work now. – Jake Kaupp Dec 06 '16 at 17:44