1

I have a data frame with two qualitative variables (Q1, Q2) which are both measured on a scale of LOW, MEDIUM, HIGH and a continuous variable CV on a scale 0-100.

s = 5
trial <- data.frame(id = c(1:s), 
                Q1 = ordered(sample(c("LOW","MED","HIGH"),size=s,replace=T)), 
                Q2 = ordered(sample(c("LOW","MED","HIGH"),size=s,replace=T)), 
                CV = runif(s,0,100))

I need to use ggplot to show a faceted plot (preferably a horizontal boxplot/jitter) of the continous variable for each qualitative variable (x2) for each level (x3). This would result in a 3 x 2 layout.

As I'm very new to ggplot I'm unsure how this should be achieved. I've played with qplot and and can't work out how to control the facets to display both Q1 and Q2 boxplots on the same chart!!

Do I need to run multiple qplots to the same window (in base I would use par to control layout) or can it be achieved from a single command. Or should I try to melt the data twice?

trial = rbind(data.frame(Q = "Q1",Level = trial[,2], CV = trial[,4]),
          data.frame(Q = "Q2",Level = trial[,3], CV = trial[,4]))

I'll keep trying and hope somebody can provide some hints in the meantime.

Matt Weller
  • 2,684
  • 2
  • 21
  • 30

1 Answers1

2

I'm not entirely clear on what you want, but maybe this helps:

ggplot(trial, aes(Level, CV)) + 
   geom_boxplot() + 
   geom_jitter() + 
   facet_wrap(~Q) + 
   coord_flip() 
Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113
  • This helps a lot, thanks. Super solution, I have a lot to learn about ggplot! – Matt Weller Jun 11 '12 at 21:05
  • 1
    sure. if you want to get HIGH, MED, LOW in the natural order, I'd recommend changing that variable to numeric and then adding labels to the plot with scale_y_discrete(labels=c('HIGH', 'MED', 'LOW')) – Matthew Plourde Jun 11 '12 at 21:22
  • 2
    @MattWeller +1, This seems to get what you asked for, but you also might consider using the fill color instead of facets... use the same code above without the `facet_wrap` call and add `fill = Q` to the `aes` call. – Gregor Thomas Jun 11 '12 at 21:32
  • In my real data that variable is in fact an ordered factor so it seems to be displaying correctly. The only pain is the values in the field which I need to remove... – Matt Weller Jun 11 '12 at 21:36
  • na.omit might help you with that – Matthew Plourde Jun 11 '12 at 21:38