As far as I can tell facet_wrap
fills by row. In the same way you can specify how to fill a matrix
with byrow
I was hoping you could do the same with facet_wrap. I know I could reorder the levels of a factor to plot in this maner but this seems like a bit of work if there's a shorter method that I'm overlooking.
library(ggplot2)
ggplot(mtcars, aes(x=gear, y=mpg, fill=vs)) +
geom_bar(position="dodge", stat="identity") +
facet_wrap(~ carb, ncol=2) #fills by row
How can we fill by column?
While facet_grid shows the labels at the margins of the facet plot, facet_wrap creates a label for each plot panel.
facet_wrap() makes a long ribbon of panels (generated by any number of variables) and wraps it into 2d. This is useful if you have a single variable with many levels and want to arrange the plots in a more space efficient manner. You can control how the ribbon is wrapped into a grid with ncol , nrow , as.
facet_grid() forms a matrix of panels defined by row and column faceting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data.
Facet plots, also known as trellis plots or small multiples, are figures made up of multiple subplots which have the same set of axes, where each subplot shows a subset of the data.
This feature is implemented in the current development version of ggplot2 on github. This commit implements a new parameter dir
of facet_wrap
, so you'd simply do
## "v" for vertical or "h" for horizontal (the default)
ggplot(...) + facet_wrap(~ carb, ncol=2, dir="v")
Note that this feature is currently not available in the version on CRAN.
It can be done by converting faceting variable into factor and then re-leveling it. In function relevel.byrow
I used matrix(..., byrow=T)
for level ordering, then converted this matrix into a vector using c()
function and then re-leveled factor.
#number of columns
nc <- 2
level.byrow <- function(vec, nc){
fac <- factor(vec) #if it is not a factor
mlev <- matrix(levels(fac), nrow=nc, byrow=T)
factor(fac, levels= c(mlev))
}
library(plyr)
ggplot(transform(mtcars, rcarb=level.byrow(carb, nc)), aes(x=gear, y=mpg, fill=vs)) +
geom_bar(position="dodge", stat="identity") +
facet_wrap(~ rcarb, ncol=nc)
I used plyr
for convenience, you can just simply write
mtcars$rcarb <- level.byrow(mtcars$carb, nc)
This also works when we don't have full facet structure, but gives couple warnings.
mtcars2 <- subset(mtcars, carb!=3)
ggplot(transform(mtcars2, rcarb=level.byrow(carb, nc)), aes(x=gear, y=mpg, fill=vs)) +
geom_bar(position="dodge", stat="identity") +
facet_wrap(~ rcarb, ncol=nc)
Result with carb==3
excluded:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With