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

标签: rggplot2legend

解决方案


您可以添加color或然后使用linetype或微调图例。这是使用数据集的示例aesscale_color_xxxscale_linetype_xxxeconomics

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 日创建。


推荐阅读