yake84 yake84 - 1 month ago 8
R Question

Horizontal barchart with facet_grid, free_x not working

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")


enter image description here

I saw this thread but couldn't get it to work:
Horizontal bar chart with facets

Thoughts?

Answer

Free space and scales 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.

enter image description here