【问题标题】:Cleanest way to add second legend for geom_segment based on color using ggplot2使用 ggplot2 根据颜色为 geom_segment 添加第二个图例的最简洁方法
【发布时间】:2021-09-14 00:05:57
【问题描述】:
library(ggplot2)
library(scales)

df = data.frame(Type = rep(c('A', 'B'), 250), Index = seq(500), Value = cumsum(rnorm(500)))

colors = hue_pal()(3)
labels = c('Alpha', 'Beta', 'Gamma')

ggplot(df, aes(Index, Value)) +
    geom_line(aes(color = Type)) +
    geom_segment(x = 200, xend = 300, y = -8, yend = -8, color=colors[1]) +  # Label as "Alpha"
    geom_segment(x = 400, xend = 500, y = -4, yend = -4, color=colors[1]) +  # Label as "Alpha" 
    geom_segment(x =   0, xend = 100, y =  0, yend =  0, color=colors[2]) +  # Label as "Beta"
    geom_segment(x = 100, xend = 200, y =  4, yend =  4, color=colors[3]) +  # Label as "Gamma"
    geom_segment(x = 300, xend = 400, y =  8, yend =  8, color=colors[3])    # Label as "Gamma" 

上面的代码产生下面的输出

我想添加第二个图例,标题为“分类”,条目“Alpha”“Beta”和“Gamma”对应于水平线段的三种颜色。 Adding a legend entry for geom_segment 的答案建议使用 scale_fill_manual 但它没有效果。我希望在 R 中有一种干净的方法来做到这一点。

【问题讨论】:

    标签: r dataframe ggplot2 time-series data-visualization


    【解决方案1】:

    这不是特别“干净”,但我想不出更好的方法:

    library(tidyverse)
    df = data.frame(Type = rep(c('A', 'B'), 250), Index = seq(500), Value = cumsum(rnorm(500)))
    scales::hue_pal()(3)
    #> [1] "#F8766D" "#00BA38" "#619CFF"
    seg_df <- data.frame(x = c(200, 400, 0, 100, 300),
                         xend = c(300, 500, 100, 200, 400),
                         y = c(-8, -4, 0, 4, 8), 
                         yend = c(-8, -4, 0, 4, 8), 
                         col = factor(c("#F8766D", "#F8766D", "#00BA38",
                                        "#619CFF", "#619CFF"),
                                      labels = c("Alpha", "Beta", "Gamma")))
    
    ggplot(df, aes(Index, Value)) +
      geom_line(aes(col = Type), show.legend = TRUE) +
      geom_segment(data = seg_df, aes(x = x, xend = xend,
                                      y = y, yend = yend,
                                      fill = col),
                   color = c("#F8766D", "#F8766D", "#00BA38",
                             "#619CFF", "#619CFF")) +
      scale_fill_manual("Classification",
                        values = c("Alpha", "Beta", "Gamma"),
                        guide = guide_legend(override.aes = list(
                          colour = c("#F8766D", "#00BA38", "#619CFF"))))
    

    我很想看看其他人是否能想出一个更简单/更清洁的方法。

    【讨论】:

      猜你喜欢
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 2017-06-21
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多