ggplot如何让图例线条颜色与主图上的颜色相匹配

ggplot how to get legend line colours match those on the main plot

我正在 ggplot 中创建一个简单的点线图,类似于下面的示例:

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

我发现与每一行关联的 'names' 的字母顺序控制着图例中的顺序,我可以使用 scale_linetype_manual 将所需的线条样式与这些行匹配。但是,我不知道如何让绘图上的线条颜色与线型图例中的颜色相匹配,它只使用最后指定的线条颜色?

这是我会做的。

  1. 而不是 3 个单独的 geom_hline 调用,让 ggplot2 根据来自 vert_data data.frame.
  2. 的数据自动绘制水平线
  3. 合并 linetypecolour 的图例。
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")