Add abline to legend

2020-02-02 03:21发布

问题:

First, sorry for posting without reproducible data. Hope you guys understand my question. This is my code. At the end of the code, I am trying to add abline. With the code, I am trying to add the name of abline to the legend but it does not work.

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)) 

As shown, I just simply add a name of the abline (let's say the name is "add") in the legend. How should I do it with my current code?

回答1:

You can add either color or linetype to aes then use scale_color_xxx or scale_linetype_xxx to fine tune the legend. Here is an example using economics dataset

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()

Edit: per OP's request, we separate linetype & color/shape legends

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))

Created on 2018-05-08 by the reprex package (v0.2.0).



标签: r ggplot2 legend