r - ggplot2 - 拆分一个图例(两个色标)并删除另一个
问题描述
我在配置情节图例时遇到了很多麻烦ggplot2
。我有两个数据框:
require(ggplot2)
mat <- rep(c("None", "wood", "steel"), each = 4)
feet = rep(seq(0,3), 3)
load = c(3:6, 4:7, 5:8)
soil <- data.frame(
feet = feet,
test = rep(1:3, each = 4),
load = c(0.1, 0.2, 0.3, 0.04,
0.5, 0.6, 0.7, 0.44,
0.8, 0.9, 1.0, 0.74)
)
dat <- rbind(
data.frame(
feet = feet,
mat = mat,
load = c(3:6, 4:7, 5:8),
SF = FALSE
),
data.frame(
feet = feet,
mat = mat,
load = c(6:9, 7:10, 8:11),
SF = TRUE
)
)
我想要一个带有图例dat$mat
和图例的情节soil$test
:
myplot <- ggplot(dat, aes(x = load, y = feet)) +
geom_line(aes(color = mat, linetype = SF)) +
geom_path(dat = soil, aes(x = load, y = feet, color = factor(test)))
myplot
我不想要名为SF
. 另外,我想将命名的图例拆分mat
为两个图例,来自data.framemat
的 (values = "none", "wood", "steel") 和来自dat
data.frame 的test
(values = 1, 2, 3) soil
.
我已经尝试过theme(legend.position = "none")
,以及许多其他各种代码组合,如果我将它们全部列出,它们会填满页面。感谢您提供的任何帮助。
解决方案
更新-此答案中提供了更好的选择。我会离开这个,因为在某些情况下可能仍然需要使用虚假美学的黑客传说。
正如@MM 正确所说的那样- ggplot 不想为一种美学画两个图例。
我真的希望您不会经常需要执行以下 hack 之类的操作:
做一个假的美学(我选择alpha
),并手动定义每条线的颜色。override.aes
然后手动
更改您的图例键。
如果您要显示的数据不止这些,请考虑使用不同的可视化/数据分离方式。一个非常好的事情是刻面。
library(ggplot2)
library(dplyr)
ggplot(dat, aes(x = load, y = feet)) +
geom_line(aes(color = mat, linetype = SF)) +
geom_path(dat = filter(soil,test ==1),
aes(x = load, y = feet, alpha = factor(test)), color = 'red') +
geom_path(dat = filter(soil,test ==2),
aes(x = load, y = feet, alpha = factor(test)), color = 'brown') +
geom_path(dat = filter(soil,test ==3),
aes(x = load, y = feet, alpha = factor(test)), color = 'green') +
scale_alpha_manual(values = c(rep(1,3))) +
scale_linetype(guide = FALSE) +
guides( alpha = guide_legend(title = 'test',
override.aes = list(color = c('red','brown','green'))))
推荐阅读
- neo4j - 如何在 Neo4J 中查询多个项目,按优先顺序只返回一个?
- r - github 操作找不到我的 R 包的文件
- javascript - 使用 RegEx 替换自定义组件
- oauth - ETrade api - 无效的消费者密钥和/或会话令牌
- angular - 如何只订阅一次可观察的
- java - Selenium 图像处理/去除水印
- excel - VBA 和条件格式的异常 - Excel 错误?
- flutter - 为什么有状态/无状态小部件扩展而不实现?
- microsoft-graph-teams - 通道消息的 Microsoft Graph API 增量查询从不返回 deltaLink
- python - 尝试使用秘密模块为 Discord 机器人生成秘密(假)银行号码,但号码会重新生成