0

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.

1
  • I would like to have two different y axes. With on the left the count and an secondary on the right, the average. Commented Mar 7, 2019 at 15:08

1 Answer 1

1

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

dual y-axis

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.