Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change order of boxplots when using ggplot2?

This question follows from this other one. I was unable to implement answers there.

Define:

df2 <- data.frame(variable=rep(c("vnu.shr","vph.shr"),each=10),         value=seq(1:20)) 

Plot:

require(ggplot2) qplot(variable,value, data=df2,geom="boxplot")+ geom_jitter(position=position_jitter(w=0.1,h=0.1)) 

I would like to have the boxplots in the reverse order (e.g. one in right on left and so on).

I have tried various ways of reordering the factors using levels, ordered, relevel, rev and so on, but I simply cannot seem to get the syntax right.

like image 441
Fred Avatar asked Jul 29 '11 00:07

Fred


People also ask

How do you format a boxplot?

The format is boxplot(x, data=), where x is a formula and data= denotes the data frame providing the data. An example of a formula is y~group where a separate boxplot for numeric variable y is generated for each value of group.

What is boxplot jitter?

The use of jitter is a great technique in dot plots, box plots with dots, and scatter plots. Jitter is a random value (or for our purposes pseudo-random) that is assigned to the dots to separate them so that they aren't plotted directly on top of each other.

What do Ggplot boxplots show?

The boxplot compactly displays the distribution of a continuous variable. It visualises five summary statistics (the median, two hinges and two whiskers), and all "outlying" points individually.


2 Answers

Have you tried this:

df2$variable <- factor(df2$variable,     levels = c('vph.shr','vnu.shr'),ordered = TRUE) 

I just picked an ordering there, since my system is configured slightly differently than yours I suspect, so my 'default ordering' may differ. But you can just switch the position of levels when specifying them.

A few other options, depend on your tastes:

For just reversing the current ordering:

factor(df2$variable,levels = rev(levels(df2$variable)),ordered = TRUE) 

or you can use subsetting to specify a specific ordering if you don't want to type out each level by hand:

factor(df2$variable,levels = levels(df2$variable)[1:2],ordered = TRUE) 
like image 175
joran Avatar answered Sep 23 '22 15:09

joran


You've already accepted a (perfectly fine) solution, but here's another option using relevel(). I'm not sure why it wasn't working for you?

#default plot ggplot(df2, aes(variable, value)) + geom_boxplot() 

enter image description here

#Reverse reverse! df2$variable2 <- with(df2, relevel(variable, "vph.shr")) ggplot(df2, aes(variable2, value)) + geom_boxplot() 

enter image description here

like image 35
Chase Avatar answered Sep 25 '22 15:09

Chase