I am trying to plot multiple plots using facet_grid()
, where I would like to have for each facet, a subset of different factor levels, plotted along the X-axis in manual order.
Basically I want to plot top 5 countries (manually defined) on the each X axis, and I can use an alternative solution with grid.arrange()
(see example), but I would like to make it with facet_grid()
or facet_wrap()
to keep the same aesthetics as with the rest of my plots.
I could find some answers to sort facets by factor level, and I tried playing with the order aesthetic, but without success, so I am wondering if there is a way to do something like this, even though I am aware that faceting in ggplot isn't designed with modifying the axes in mind. I would appreciate some advices on this.
Here is a reproducible example of what I want (manually defined order on X-axes).
library(reshape)
library(ggplot2)
library(gridExtra)
# Load data
mtcars_melt <- melt(mtcars)
# Subset data
set1 <- subset(mtcars_melt, variable == "mpg" | variable == "wt" | variable == "qsec")
set2 <- subset(mtcars_melt, variable == "gear" | variable == "cyl" | variable == "mpg")
set3 <- subset(mtcars_melt, variable == "drat" | variable == "vs" | variable == "mpg")
# Order factors
set1$variable <- factor(set1$variable, levels = c("mpg", "wt", "qsec"))
set2$variable <- factor(set2$variable, levels = c("mpg", "gear", "cyl"))
set3$variable <- factor(set3$variable, levels = c("vs", "mpg", "drat"))
# Make plots
plot1 <- ggplot(set1, aes(x = variable, y = value)) + ylim(0, 35) + geom_boxplot()
plot2 <- ggplot(set2, aes(x = variable, y = value)) + ylim(0, 35) + geom_boxplot()
plot3 <- ggplot(set3, aes(x = variable, y = value)) + ylim(0, 35) + geom_boxplot()
grid.arrange(plot1, plot2, plot3, ncol = 3)
Here is the example of the plot: