r - 如何在使用 ggplot2 制作的单个图中组合填充(列)和颜色(点和线)图例?
问题描述
在图表中,我有列和点。我正在尝试统一传说;我已经在秤上放了相同的名字,但它们仍然是分开的。有人可以帮我解决这个问题吗?
library(ggplot2)
X <- factor(c("a", "b"))
Y1 <- c(10, 15)
Y2 <- c(22, 23)
df <- data.frame(X, Y1, Y2)
ggplot(data = df, aes(x = X,
group = 1)) +
geom_col(aes(y = Y1,
fill = "Y1")) +
geom_line(aes(y = Y2,
color = "Y2")) +
geom_point(aes(y = Y2,
color = "Y2")) +
scale_fill_manual(name = "Legend",
values = "blue") +
scale_color_manual(name = "Legend",
values = "red")
解决方案
要合并图例,您还必须在填充和色标中使用相同的值。override.aes
此外,您必须通过使用以下参数删除“Y2”图例键的填充颜色来稍微调整图例guide_legend
:
编辑感谢@aosmith 的评论。为了使这种方法适用于 ggplot2 版本 <=3.3.3,我们必须明确设置limits
两个比例。
library(ggplot2)
X <- factor(c("a", "b"))
Y1 <- c(10, 15)
Y2 <- c(22, 23)
df <- data.frame(X, Y1, Y2)
ggplot(data = df, aes(x = X,
group = 1)) +
geom_col(aes(y = Y1,
fill = "Y1")) +
geom_line(aes(y = Y2,
color = "Y2")) +
geom_point(aes(y = Y2,
color = "Y2")) +
scale_fill_manual(name = "Legend",
values = c(Y1 = "blue", Y2 = "red"), limits = c("Y1", "Y2")) +
scale_color_manual(name = "Legend",
values = c(Y1 = "blue", Y2 = "red"), limits = c("Y1", "Y2")) +
guides(color = guide_legend(override.aes = list(fill = c("blue", NA))))
推荐阅读
- angularjs - AngularJS + nginx 代码库是否应该被 docker 化
- java - 为什么JPA合并操作会导致更新前多选?
- npm - 我们如何验证“npm login”成功并且令牌没有过期?
- angular - 如何在打字稿中使用模板的“as”关键字定义的变量
- c++ - 二维矢量输入和通过函数显示
- postgresql - Postgres通知中的别名列名
- agens-graph - 如何删除 AgensGraph 上的节点?
- sql - 一个主查询中的两个查询
- jquery - 左菜单 Jquery 切换在 React JS 中不起作用
- sql-server - 使用 Pentaho 水壶 Spoon 将数据从 Mysql 导入 Neo4j