Grouped and Stacked Bar Charts in R
Sometimes you have a chart that looks like one of these. You have a grouped chart that shows one thing and a stacked chart that shows another. But you really want to show the continent of origin and the condition in one chart.
Maybe the chart you want looks a lot like this:
First we load ggplot2
so we can make our charts. Then we make some data and preview it. set.seed(2022)
makes sure that our data is the same every time.
Our first instinct might be to throw both charts together using grid.arrange
from the gridextra
package. While this does show the information we want, it’s not pretty and doesn’t show the data the way we want it to.
Not sure what to do, we come up with lots of plots that are almost right, but not quite.
That last one looks like it could be promising. How did we do it?
We use ggplot
to set up the pipeline, geom_bar
to create the bar chart, and then facet_wrap
is what gives us the four separate charts in one, with one mini-chart for each species. If we can move the charts to be side-by-side, we’ll be a lot closer to the desired outcome. We can use facet_grid
instead of facet_wrap
to accomplish that.
This looks much better, but we want it to look like one cohesive plot, rather than four smaller plots.
I’m going to show you the code that does it, then walk through it so everything makes sense.
This looks pretty good and is exactly what we wanted. Like the charts before, we get 90% of the way there with ggplot
, geom_bar
, and facet_grid
. The additions here are the switch = "x"
argument in facet_grid
, which moves the group panel with the species from the top of the chart to the bottom. Moving the strip.placement
outside makes sure that the conditions are listed between the species and the chart. Making strip.background
empty with a white border allows the group panel with the species to blend in with the white background of the chart. Lastly, changing the panel.spacing
to -.01
removes the small gap between each panel so that the chart appears to be one cohesive unit.
The code for all the charts in this article is available here. If you want to see more from me, check out my GitHub or guslipkin.github.io. If you want to hear from me, I’m also on Twitter at guslipkin.
Gus Lipkin is a Data Scientist, Business Analyst, and occasional bike mechanic