In this tutorial, we will see how to make a grid of bar plots using facet_grid()
. Such a grid may be useful when your data set contains several categorical predictor variables, and displaying the data in a single graph makes it hardly comprehensible. If you are not so familiar with bar plots or facet_grid()
, have a quick look at these two pages:
We will plot the precipitations recorded monthly in 2017, 2018 and 2019 at two Norwegian locations: Lygra and Østerbø. We will thus have three categorical variables: month
, year
and location
, and one response variable precipitations
. Here is the code for the dataframe:
# dataframe
df <- data.frame(location, year, month, precipitations)
# structure of the dataframe
str(df)
## 'data.frame': 72 obs. of 4 variables:
## $ location : Factor w/ 2 levels "Lygra","Østerbø": 1 1 1 1 1 1 1 1 1 1 ...
## $ year : Factor w/ 3 levels "2017","2018",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ month : Factor w/ 12 levels "Jan","Feb","Mar",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ precipitations: num 135.8 88.4 91 111.7 31 ...
Our plan is to make a matrix displaying 6 panels, each of which is a bar plot. In these bars plot, the predictor variable month
and the response variable precipitations
shall be plotted on the X- and Y-axis, respectively. Eventually the matrix shall show location
in columns and year
in rows. To obtain this matrix, we must:
aes(x = month, y = precipitations)
,geom_col()
,facet_grid()
like this: facet_grid(year~location)
.Here is the code, and the corresponding faceted plot:
ggplot(df, aes(x = month, y = precipitations)) +
geom_col() +
facet_grid(year~location)
If the plan was to set up a matrix with location
in rows and year
in columns, we should have inverted the variables in facet_grid()
:
ggplot(df, aes(x = month, y = precipitations)) +
geom_col() +
facet_grid(location~year)
However, in this particular case, the X-axis is overloaded and the labels are unreadable.
You may improve the look of a grid by tuning the labels of the matrix. This is further explained HERE.
This data set may be alternatively plotted in the form of a grid of clustered/grouped bars. HERE is a tutorial for making such a plot.