首页 > 解决方案 > 带几何线的条形图叠加

问题描述

这是数据示例:

S   P   C   P_int C_int
10  20  164 72    64 
20  550 709 92    89 
30  142 192 97    96 
40  45  61  99    98 
50  12  20  99    99 
60  5   6   99    99 
70  2   2   99    99 
80  4   1   99    99 
90  1   0   10    99 
100 0   1   10    99

假设我有一个名为 df 的数据框,其目的是使用变量 P 和 C 制作条形图,并使用变量 P_int 和 C_int 的总和覆盖折线图。目前我有这些代码行来创建条形图:

final <- df %>% tidyr::gather(type, value, c(`P`, `C`))
ggplot(final, aes(S))+
  geom_bar(aes(y=value, fill=type), stat="identity", position="dodge")

我想不通的事情是将变量 P_int 和 C_int 的总和绘制为一个折线图,该折线图覆盖在上面的图上,并带有第二个 Y 轴。将不胜感激任何帮助。

标签: rggplot2bar-chart

解决方案


你需要这样的东西吗?

library(ggplot2)
library(dplyr)

ggplot(final, aes(S))+
  geom_bar(aes(y=value, fill=type), stat="identity", position="dodge") + 
  geom_line(data = final %>% 
                    group_by(S) %>% 
                    summarise(total = sum(P_int + C_int)), 
            aes(y = total), color = 'blue') +
  scale_y_continuous(sec.axis = sec_axis(~./1)) +
  theme_classic()

在此处输入图像描述

我保持辅助 y 轴的比例与主 y 轴相同,因为它们在同一范围内,但您可能需要根据您的实际数据进行调整。


推荐阅读