首先,抱歉没有可重复的数据发布。希望你们理解我的问题。这是我的代码。在代码的最后,我试图添加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”)。我应该如何使用我当前的代码呢?
答案 0 :(得分:3)
您可以将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
&amp; 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 package(v0.2.0)创建于2018-05-08。