r - 将 abline 添加到图例
问题描述
首先,很抱歉在没有可重复数据的情况下发布。希望你们能理解我的问题。这是我的代码。在代码的末尾,我正在尝试添加 abline。使用代码,我试图将 abline 的名称添加到图例中,但它不起作用。
ggplot(aes(x = week_id2, y = Index, color = Chain2, linetype = Chain2, group = Chain2),
data = data00 +
geom_point(aes(shape=Chain2), size = 3) +
geom_line() +
scale_linetype_manual(values=c("twodash", "dashed", "dotted", "dotdash", "longdash")) +
scale_shape_manual(values=c(1:5)) +
xlab("Week") +
ylab("Index") +
geom_hline(aes(yintercept=1))
如图所示,我只是简单地在图例中添加了 abline 的名称(假设名称为“add”)。我应该如何使用我当前的代码来做到这一点?
解决方案
您可以添加color
或然后使用linetype
或微调图例。这是使用数据集的示例aes
scale_color_xxx
scale_linetype_xxx
economics
library(tidyverse)
df <- economics %>%
select(date, psavert, uempmed) %>%
gather(key = "variable", value = "value", -date)
ggplot(df, aes(x = date, y = value)) +
geom_line(aes(color = variable), size = 1) +
geom_hline(aes(yintercept = 10, color = "My line")) +
scale_color_brewer(palette = "Dark2",
breaks = c("psavert", "uempmed", "My line")) +
theme_minimal()
ggplot(df, aes(x = date, y = value)) +
geom_line(aes(color = variable, linetype = variable), size = 1) +
geom_hline(aes(yintercept = 10, color = "My line", linetype = "My line")) +
scale_color_brewer(palette = "Dark2",
breaks = c("psavert", "uempmed", "My line")) +
scale_linetype_manual(values = c("twodash", "dashed", "dotted"),
breaks = c("psavert", "uempmed", "My line")) +
theme_minimal()
编辑:根据 OP 的要求,我们分开linetype
&color/shape
传说
ggplot(df, aes(x = date, y = value)) +
geom_line(aes(color = variable), size = 0.75) +
geom_point(aes(color = variable, shape = variable)) +
geom_hline(aes(yintercept = 10, linetype = "My line")) +
scale_color_brewer(palette = "Dark2",
breaks = c("psavert", "uempmed")) +
scale_linetype_manual("", values = c("twodash"),
breaks = c("My line")) +
scale_shape_manual(values = c(17, 19)) +
# Set legend order
guides(colour = guide_legend(order = 1),
shape = guide_legend(order = 1),
linetype = guide_legend(order = 2)) +
theme_classic() +
# Move legends closer to each other
theme(legend.title = element_blank(),
legend.justification = "center",
legend.spacing = unit(0.1, "cm"),
legend.spacing.y = unit(0.05, "cm"),
legend.margin = margin(0, 0, 0, 0),
legend.box.margin = margin(0, 0, 0, 0))
由reprex 包(v0.2.0) 于 2018 年 5 月 8 日创建。
推荐阅读
- java - 取当前年份并将其设置为日历
- java - 从 CloseableHttpClient.execute() 捕获异常所需的代码结构
- sql - 如何在 Oracle SQL 中新创建的列中的两个字符串值之间随机插入?
- python - 如何根据其他两个列表过滤一个列表
- python - 如何在 protobuf 中调试无效的 utf-8?
- selenium - python selenium xpath 找不到元素
- php - 如何验证非法偏移警告?
- python-3.x - 如何从 Wappalyzer 隐藏 Python 和 Django 技术
- google-chrome - 如何通过谷歌浏览器从网站下载音频
- excel - VBA Excel 2019:打开时为所有用户关闭工作簿的超链接