Chelsea Acres Chelsea Acres - 4 days ago 8
R Question

Using ggplot2 to graph counts of multiple x variables together

I'm using an csv of survey data. Each row is an individual survey. One of the questions asked is "What activities do you take part in at the beach?". There is a column for each of the 12 activities listed. If an interviewer said they took part in an activity, the csv has a 1 and if they did not it has a 2. I want to create a barplot in ggplot2 showing how many people participate in all activities, and then use cross tabs (gender, location, age, etc.) for fill later on.

I've done this in base r:

swim.all.13=table(b13$actswim)
surf.all.13=table(b13$actsurf)
walk.all.13=table(b13$actwalk)
relax.all.13=table(b13$actrelx)
shell.all.13=table(b13$actshell)
picnic.all.13=table(b13$actpic)
sun.all.13=table(b13$actsun)
read.all.13=table(b13$actread)
fish.all.13=table(b13$actfish)
work.all.13=table(b13$actwork)
eat.all.13=table(b13$acteat)

act.all.13.test=cbind(swim.all.13,surf.all.13,walk.all.13,relax.all.13,shell.all.13,picnic.all.13,sun.all.13,read.all.13,fish.all.13,work.all.13,eat.all.13)
act.all.13=act.all.13.test[2,]

barplot(act.all.13,xlab="Activity",ylab="NUmber of Responses",names.arg=" ",legend=c("Swim", "Surf", "Walk", "Relax", "Shell", "Picnic", "Sun", "Read", "Fish", "Work", "Eat"),main="What activities do you engage in while at the beach?")


Which gives me the table I am looking for, but looks like complete garbage. I prefer graphing in ggplot2, which is what the rest of the survey data is graphed in.

Screenshot of CSV I'm working with

Answer

Edited based on OP Comment:

How about

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

Basically converts the data into a tidy dataset which is tall rather than wide, filters just for 1 as the value and uses dplyr::count() to aggregate and feed into plot.

Edit: to facet by Gender:

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