r - R使用scale_linetype_manual在ggplot图例中旋转vline
问题描述
我有以下简单的 MWE。我希望我的图例中的绿线是一条垂直线。一旦我在 geom_vline 中启用 show.legend,它还会在图例中的每一行添加一条垂直线。有没有人暗示我如何做到这一点?
library(ggplot2)
ggplot(data = df) +
geom_line(aes(x = a, y = b, colour = "one", linetype = "one"), size = 2) +
geom_line(aes(x = a, y = c, colour = "two", linetype = "two"), size = 2) +
geom_vline(aes(xintercept = 0.5, colour = "three", linetype = "three"), alpha = 1, show.legend = F) +
scale_colour_manual("",
breaks = c("one", "two", "three"),
values = c("blue", "red", "green")) +
scale_linetype_manual("",
breaks = c("one", "two", "three"),
values = c("dashed", "solid", "solid")) +
theme_bw() +
theme(legend.key.size = unit(2, "cm"),
legend.position = c(0.05, 0.995), legend.justification = c(0.05, 0.995))
解决方案
调整此答案以实现您想要的结果的一个选项是使用自定义键字形功能。这种方法的一个缺点是它会根据线的条件在color
水平线或垂直线之间进行选择,也就是说,如果您更改颜色,您也必须调整条件。
编辑要在图例中获得正确的线条大小,有两个选项。一种是在自定义键字形函数中设置大小。第二种选择是通过using的override.aes
参数设置大小guide_legend
guides(linetype = guide_legend(override.aes = list(size = c(2, 2, .5))))
library(ggplot2)
# Custom Key Glyph. Vertical Line if color = "green". Horizontal Line otherwise
draw_key_cust <- function(data, params, size) {
if (data$colour == "green") {
data$size <- .5
draw_key_vpath(data, params, size)
} else {
data$size <- 2
draw_key_path(data, params, size)
}
}
ggplot(data = df) +
geom_line(aes(x = a, y = b, colour = "one", linetype = "one"), size = 2, key_glyph = "cust") +
geom_line(aes(x = a, y = c, colour = "two", linetype = "two"), size = 2, key_glyph = "cust") +
geom_vline(aes(xintercept = 0.5, colour = "three", linetype = "three"), alpha = 1, key_glyph = "cust") +
scale_colour_manual(breaks = c("one", "two", "three"),
values = c("blue", "red", "green")) +
scale_linetype_manual(breaks = c("one", "two", "three"),
values = c("dashed", "solid", "solid")) +
labs(color = NULL, linetype = NULL) +
theme_bw() +
theme(legend.key.size = unit(2, "cm"),
legend.position = c(0.05, 0.995),
legend.justification = c(0.05, 0.995))
数据
set.seed(42)
df <- data.frame(
a = runif(100),
b = runif(100),
c = runif(100)
)
推荐阅读
- .net - 递归地将字符串拆分为字符列表
- java - java - 如何在Java中找到年月和日中的两个日期之间的差异?
- automata - 正则表达式:所有不包含子字符串 'bb' 的字符串的语言
- asp.net - ASP.Net Core - OAuth 令牌端点失败:状态:BadRequest
- sql-server - 在 JPA 实体的存储过程中使用别名
- c# - 如何从 c# 中的数据 Data Grid 视图中选中 false 值并将其存储在数据库 sql server 上
- android - 如何将flutter项目迁移到androidx
- google-cloud-platform - 从私有仓库创建实例模板
- c# - 使用 IdentityServer3 生成访问令牌,无需密码
- c# - 从另一个按钮调用 DataGridView 的 CellContentClick 方法