r - 带几何线的条形图叠加
问题描述
这是数据示例:
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 轴。将不胜感激任何帮助。
解决方案
你需要这样的东西吗?
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 轴相同,因为它们在同一范围内,但您可能需要根据您的实际数据进行调整。
推荐阅读
- python - 在 bash 脚本中导入许多 python 文件
- django - 显示所有有在场和不在场状态的员工
- node.js - 如何使用 Socket io 从函数中发出数据
- python - 仅当连续时才在另一个列表中查找列表项的索引
- amazon-web-services - 为什么在浏览器中连接到 ec2 实例失败这么多次
- html - 如何在单独的元素中将圆角与边框对齐?
- java - 如何将浮点数组转换为位图或 Uri 以将其设置为图像
- mysql - Symfony 在查询中传递自定义 sql 参数
- reactjs - React 应用程序在部署到 Heroku 时无法加载配置“airbnb”
- mysql-error-2002 - 错误 2002 (HY000):无法通过 ubuntu 18.04 LTS 中的套接字“/var/run/mysqld/mysqld.sock”连接到本地 MySQL 服务器