简体   繁体   English

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

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

I'm creating a simple point and line plot in ggplot similar to the example below:我正在 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")

示例图

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.我发现与每一行关联的“名称”的字母顺序控制了图例中的顺序,我可以使用 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?但是,我无法弄清楚如何让绘图上的线条颜色与线型图例中的颜色相匹配,它只使用最后指定的线条颜色?

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 .而不是 3 个单独的geom_hline调用,让ggplot2根据来自vert_data data.frame的数据自动绘制水平线。
  2. Combine legends for linetype and colour .结合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")

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM