0
votes

I would like to plot multiple variables on the same boxplot using ggplot. When doing so, it messes up the order of the categories and the variables. Here is my MWE:

require(reshape2)
require(ggplot2)

var1 <- c('tall', 'tall', 'medium', 'tall', 'short', 'medium', 'short', 'short', 'medium', 'tall', 'short', 'medium', 'medium', 'short')
var2 <- c('easy', 'ok', 'difficult', 'ok', 'easy', 'ok', 'difficult','easy', 'easy', 'easy', 'difficult', 'ok', 'difficult', 'easy')
group <- c('a', 'a', 'a', 'b', 'b', 'a', 'b', 'b', 'a', 'b', 'a', 'b', 'b', 'a')
score <- c('67', '45', '63', '74', '34', '58', '55', '48', '67', '71', '48', '60', '61', '53')
dat <- data.frame(var1, var2, group, score=as.numeric(score))

datl <- melt(dat, measure.vars='score')


s1 <- ggplot(data=datl, aes(x=var1, y=value, fill=group)) + 
  geom_boxplot()
s2 <- ggplot(data=datl, aes(x=var2, y=value, fill=group)) + 
  geom_boxplot()

x1 <- ggplot(data=datl, aes(y=value, fill=group)) + 
  geom_boxplot(aes(x=var1)) +
  geom_boxplot(aes(x=var2))

And here are the corresponding graph: s1+s2 and x1. I would like to keep the order of s1+s2 in one graph such as x1. s1+s2

x1

Any help welcome.

1
You can manually set the limits of scale_x_discrete. - Axeman
Thank you. It works fine. I'll post the answer. Although I may go back to the multiplot form without legend and y-axis. It seems more representative by separating categories within a variable differently than variables between themselves. Best, - jejuba

1 Answers

0
votes

the answer suggested by Axeman is to add this line.

x1 <- x1 + scale_x_discrete(name ="Categories", limits=c(as.character(levels(datl$var1)), as.character(levels(datl$var2))))