简体   繁体   中英

Add secondary axis to stacked bar chart

I have this code which creates the plot below

sec_axis_data <- mpg %>%
  group_by(manufacturer) %>%
  summarise(entries = n())

p <- ggplot(mpg, aes(x = manufacturer, fill = class == "compact")) +
  geom_bar(position = "fill") +
  scale_fill_manual(values = c('blue', 'red')) +
  scale_y_continuous(sec.axis = sec_axis(~. * 50))
p

在此处输入图像描述

However, I'm not sure how to get the secondary axis data to display properly as a line across the plot? When, for example, I try:

p <- ggplot(mpg, aes(x = manufacturer, fill = class == "compact")) +
  geom_bar(position = "fill") +
  scale_fill_manual(values = c('blue', 'red')) +
  scale_y_continuous(sec.axis = sec_axis(~. * 50)) +
  geom_line(data = sec_axis_data, aes(x = manufacturer, y = entries))
p

... I get an error. I think the issue is linked to the different lengths of the data for mpg and sec_axis_data, but I'm not sure how to resolve this.

You were quite close of the solution.

You need to add inherit.aes = FALSE because of the fill argument not find in your second dataframe.

Also, to set the appropiate value, you need to divide your "entries" values by the same ratio you used for building the second axis in sec.axis function:

library(ggplot2)

ggplot(mpg, aes(x = manufacturer, fill = class == "compact")) +
  geom_bar(position = "fill", alpha = 0.5) +
  scale_fill_manual(values = c('blue', 'red')) +
  scale_y_continuous(sec.axis = sec_axis(~. * 50, name = "Second axis")) +
  geom_line(inherit.aes = FALSE, data = sec_axis_data, 
            aes(x = manufacturer, y = entries/50, group = 1), size = 2)

在此处输入图像描述

Does it answer your question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM