Home > Back-end >  ggplot how to get legend line colours match those on the main plot
ggplot how to get legend line colours match those on the main plot

Time:06-01

I'm creating a simple point and line plot in ggplot similar to the example below:

dat <- iris %>%                               # dummy data
       select(Sepal.Length) %>% 
       mutate(Type = "Sepal.Length")

ggplot()  
geom_point(data = dat, aes(x = as.numeric(row.names(dat)), y = Sepal.Length, shape = Type), colour = "orange")  
scale_shape_manual(values =  10)  
geom_hline(aes(yintercept = 6, linetype = 'C Red line'), colour = "red", size = 0.5)  
geom_hline(aes(yintercept = 5, linetype = 'A Blue line'), colour = "darkblue", size = 0.5)  
geom_hline(aes(yintercept = 7, linetype = 'B Green line'), colour = "forestgreen", size = 0.5)  
scale_linetype_manual(values = c('solid', 'dashed', 'dotted'))  
labs(linetype = "Line legend")  
labs(shape = "Point legend")

Example plot

I'ev worked out that the alphabetical order of the 'names' associated with each line controls the order in the legend and I can match a desired line style to those lines using scale_linetype_manual. However, I cannot work out how to get the colours of the lines on the plot to be matched by the colours in linetype legend, which just uses the last specifed line colour?

CodePudding user response:

Here is what I would do.

  1. Instead of 3 individual geom_hline calls, let ggplot2 automatically plot horizontal lines based on data from a vert_data data.frame.
  2. Combine legends for linetype and colour.
vert_data <- data.frame(
    yintercept = c(6, 5, 7),
    name = c("C Red line", "A Blue line", "B Green line"),
    linetype = c("dotted", "solid", "dashed"),
    colour = c("red", "darkblue", "forestgreen"))

ggplot()  
    geom_point(
        data = dat, 
        aes(x = as.numeric(row.names(dat)), y = Sepal.Length, shape = Type), 
        colour = "orange")  
    scale_shape_manual(values =  10)  
    geom_hline(
        data = vert_data,
        aes(yintercept = yintercept, linetype = name, colour = name),
        size = 0.5)  
    scale_linetype_manual(
        "Line legend", values = setNames(vert_data$linetype, vert_data$name))  
    scale_colour_manual(
        "Line legend", values = setNames(vert_data$colour, vert_data$name))  
    labs(shape = "Point legend")

enter image description here

  • Related