簡體   English   中英

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

示例圖

我發現與每一行關聯的“名稱”的字母順序控制了圖例中的順序,我可以使用 scale_linetype_manual 將所需的線條樣式與這些線條匹配。 但是,我無法弄清楚如何讓繪圖上的線條顏色與線型圖例中的顏色相匹配,它只使用最后指定的線條顏色?

這就是我要做的。

  1. 而不是 3 個單獨的geom_hline調用,讓ggplot2根據來自vert_data data.frame的數據自動繪制水平線。
  2. 結合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