We will use ggplot()
to draw such a combined chart. Before going any further, if you are not so familiar with line plots and vertical bar plots, have a quick look at these pages:
The dataframe for this tutorial is as follows:
# dataframe
df <- data.frame(ID, series1, series2)
# structure of the dataframe
str(df)
## 'data.frame': 12 obs. of 3 variables:
## $ ID : Factor w/ 12 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ series1: num 45.3 43.5 45.7 25.8 39.2 ...
## $ series2: num 5.59 10.47 11.44 7.54 10.61 ...
The following codes draw a bar plot based on series1
and a line plot based on series2
:
ggplot(df, aes(x = ID, y = series1)) + # bar plot
geom_col(size = 1, color = "darkblue", fill = "white")
ggplot(df, aes(x = ID, y = series2)) + # line plot
geom_line(size = 1.5, color="red", group = 1)
Now, we “just” have to merge these two plots into one figure. But we have to be careful when mapping the data for each plot. Both plots use ID
for the X-axis; however, the line plot uses series2
for its Y-axis, while the column plot uses series
1. This means that we must create a mapping for each of the plot by using aes()
twice, one for each geom
:
ggplot(df) +
geom_col(aes(x = ID, y = series1), size = 1, color = "darkblue", fill = "white") +
geom_line(aes(x = ID, y = series2), size = 1.5, color="red", group = 1)
Alternatively, since ID
is the predictor variable for both the line plot and the bar plot, we can place aes(ID)
in ggplot()
, but we still have to use aes()
to map the response variable in each geometry:
ggplot(df, aes(x = ID)) +
geom_col(aes(y = series1), size = 1, color = "darkblue", fill = "white") +
geom_line(aes(y = series2), size = 1.5, color="red", group = 1)
The result (now shown here) is identical to the plot above.
As you may see here, the two plot types appear correctly in the same graph, as expected. However, both use the same Y-axis and its corresponding scale. Since the range of the line plot is much lower than the column plot, the use of a secondary Y-axis with a more adapted scale is recommended. Click HERE if you want to know more about setting up a secondary Y-axis in ggplot2.
Here is the code to set up the secondary Y-axis that fits our example:
ggplot(df) +
geom_col(aes(x = ID, y = series1), size = 1, color = "darkblue", fill = "white") +
geom_line(aes(x = ID, y = 3*series2), size = 1.5, color="red", group = 1) +
scale_y_continuous(sec.axis = sec_axis(~./3, name = "series2"))
In this section, you will learn how to set/modify all the necessary elements that make a plot complete and comprehensible. Such elements are: