Add abline to legend

后端 未结 1 1047
旧时难觅i
旧时难觅i 2020-12-07 04:51

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,

1条回答
  •  悲&欢浪女
    2020-12-07 05:02

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

    0 讨论(0)
提交回复
热议问题