Reputation: 21
I need to plot a bar chart showing counts and a line chart showing the average. This all in one chart with multiple y axes.
Here is an example of the dataframe:
df <- data.frame("YearMonth" = c(20141, 20142, 20143, 20144), "Count" = c(435, 355, 360, 318), "Average" = c(107, 85, 86, 74))
How can this be done?
Thanks a lot.
Upvotes: 0
Views: 402
Reputation: 545598
{ggplot2} intentionally does not support this kind of multiple y-axes because there’s a broad consensus that they are a bad idea because they invite misinterpretation of the data. See e.g. Why not to use two axes, and what to use instead:
We believe that charts with two different y-axes make it hard for most people to intuitively make right statements about two data series. We recommend two alternatives strongly: using two charts instead of one and using indexed charts.
The only kind of secondary y-axis that {ggplot2} supports is one that’s a scaling of the primary axis, see sec_axis
. Such a secondary axis doesn’t suffer from the same problem, but it won’t work in your scenario: what you want is indeed one of the cases that {ggplot2} intentionally doesn’t support.
What you can do, though, is to duplicate a single y-axis, and overlay the bars and the averages (although it’s not clear what the bars represent in this case):
# fix the `YearMonth` column:
df$YearMonth = lubridate::ymd(paste(sub('(.)$', '0\\1', as.character(df$YearMonth)),'01'))
ggplot(df) +
aes(YearMonth) +
geom_col(aes(y = Count)) +
geom_line(aes(y = Average), size = 2, color = 'lightblue') +
scale_y_continuous(sec.axis = dup_axis(name = NULL))
Upvotes: 1