r - 将 abline 添加到图例

标签 r ggplot2 legend

首先,对于没有可重现数据的发布表示抱歉。希望你们能理解我的问题。这是我的代码。在代码的末尾,我尝试添加 abline。使用代码,我尝试将 abline 的名称添加到图例中,但它不起作用。 enter image description here

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”)。我应该如何使用当前的代码来做到这一点?

最佳答案

您可以将colorlinetype添加到aes,然后使用scale_color_xxxscale_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的要求,我们将线型颜色/形状图例分开

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 创建于 2018-05-08 (v0.2.0)。

关于r - 将 abline 添加到图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50239850/

相关文章:

用相邻列中的值替换列中的 NA

r - 使用 RStudio 的导出功能生成高分辨率 ggplot 图像的混合方式?

r - 数据分组时如何在直方图顶部添加百分比

twitter-bootstrap - Bootstrap 更改图例标记中文本的大小和字体

r - 如何在情节图例的线条顶部居中框?

matlab - 如何为子图提供共同的图例?

r - 过滤数据框上的日期

r - 在函数中调用print(ls.str())影响rep的行为

r - tidyr - 展开多列

r - GGPLOT 曲线中的不同线型和固定颜色