4
votes

I have a data set which is similar to

df <- data.frame(cbind(
  c(rep.int(x = 0, times =7), 1:3), 
  c(1, 1, 1, 0, 1, 0, 1, 1, 0, 0),
  c(1:3, 1:3, 1:3, NA)))
names(df) <- c("cars", "sex", "status")
df$sex <- factor(df$sex, labels = c("male", "female"))
df$status <- factor(df$status, labels = c("bad", "ok", "good"))
df$car <- (df$cars > 0) # Person has at least 1 car

I would like to use ggplot2 to make a faceted bar chart with the following characteristics:

  • Facet by the categorical variables (sex and status in this example)
  • Each panel contains one bar per level of that factor (e.g. male and female for "sex")
  • Each bar shows how many percent of the total observations for that level of that factor, that has at least 1 car (e.g. percent of males with at least 1 car)

How can I do this smoothly in ggplot2? (Or alternatively, do you have a better suggestion of how to represent these proportions graphically?)

1
Have you actually tried anything yet, or do you just want us to do this for you? - joran
Yes, I have. However, the results were so far from what I wanted that I chose not to include them. - Benjamin Allévius

1 Answers

4
votes
library(ggplot2)

df.long = melt(df, measure.vars=c('sex', 'status'))
df.long.summary = ddply(df.long, .(variable, value), summarize, cars=sum(cars > 0) / length(cars))

ggplot(data=df.long.summary, aes(x=value, y=cars)) +
  geom_bar(stat='identity') +
  facet_wrap(~variable, scales='free_x') +
  scale_y_continuous(formatter='percent')

enter image description here

(BTW it's even a bit simpler in the next version of ggplot2, as there will be no need to compute the summary manually because you can automatically limit the plot range to the summary instead of the raw data)