简体   繁体   English

将辅助轴添加到堆积条形图

[英]Add secondary axis to stacked bar chart

I have this code which creates the plot below我有这段代码在下面创建 plot

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?但是,我不确定如何让辅助轴数据正确显示为穿过 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.我认为这个问题与 mpg 和 sec_axis_data 的数据长度不同有关,但我不确定如何解决这个问题。

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.您需要添加inherit.aes = FALSE ,因为在您的第二个 dataframe 中找不到fill参数。

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:此外,要设置适当的值,您需要将“条目”值除以用于在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?它回答了你的问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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