Reputation: 3236
Using the mpg
dataset as an example, I want to use facet_grid()
where the only the relevant models are listed under each manufacturer.
This code seems to work (left chart)
library(ggplot2)
qplot(cty, model, data=mpg) +
facet_grid(manufacturer ~ ., scales = "free", space = "free")
But this one doesn't (right)
ggplot(mpg) +
geom_bar(aes(x = model, y = cty), stat = "identity") +
coord_flip() +
facet_grid(manufacturer ~ ., scales = "free", space = "free")
I saw this thread but couldn't get it to work: Horizontal bar chart with facets
Thoughts?
Upvotes: 3
Views: 2646
Reputation: 93871
TL;DR: space="free"
and scales="free"
don't work with coord_flip
. Instead, use geom_barh
(horizontal bar geom) from the ggstance
package, which avoids the need for coord_flip
. Details below.
space="free"
and scales="free"
don't work with coord_flip
. This doesn't matter for plotting points, because with points you can switch the x and y axes and geom_point
will still work, avoiding the need for coord_flip
. However, geom_bar
expects the value to be the y
variable and the categories to be the x
variable, so you need to use coord_flip
to get horizontal bars.
To avoid coord_flip
, you can use the horizontal geom geom_barh
from the ggstance
package, so that the free
space and scales settings in facet_grid
will work:
library(ggplot2)
library(ggstance)
ggplot(data=mpg, aes(x=cty, y=model)) +
geom_barh(stat="identity") +
facet_grid(manufacturer ~ ., scales = "free_y", space = "free_y")
Note that the code above creates a stacked bar plot, where the values of cty
mpg for all the cars of a given model
are stacked one on top of the other, which is non-sensical. You can see this if, for example, you set colour="green"
inside geom_barh
. I assume this plot is just for illustration but I wanted to point that out for completeness.
Upvotes: 6