【问题标题】:Adding a second legend to a ggplot2 graph - data points and regression lines向 ggplot2 图形添加第二个图例 - 数据点和回归线
【发布时间】:2017-06-21 14:15:36
【问题描述】:

我正在尝试为两个数据系列创建两个单独的图例。基本上我有一个数据系列和回归线,我想要一个带有回归数据的图例,最好是报告的 adjr2,以及另一个带有数据集中点的图例。我是 ggplot2 的新手,我一直无法弄清楚指南(guide_legend)。

这是我的代码。我已经设法获得了要在图例上显示的点,所以我想为虚线回归线创建第二个点。我有一列用于调整后的 r2 值,我想将其称为第二个图例。

g <- ggplot(acci_bud, aes(x = Elevation, y = DOY, color = Year)) +
       geom_errorbar(aes(ymin = DOY -se, ymax = DOY +se), width = .1, show.legend = F)
g <- g + geom_point()
g <- g + geom_abline(data = acci_elev_slope, aes(slope = slope_coeff, 
     intercept = slope_int, color = year),linetype = 'dashed', show.legend = F)

我可以用基本包制作这个情节,但我希望能够有一个用于多个数据集的基本脚本,我认为 ggplot2 更有利于这一点。

编辑:这应该是可重现的:

acci_bud <- data.frame(  Elevation = rep((seq(from = 500, to = 1250, by = 50)),7),
                   DOY = sample(75:180, 112, replace = TRUE),
                   Year = rep(2009:2015, each = 16),
                   se = 2)

acci_elev_slope <- data.frame ( year = seq(from = 2009, to = 2015, by = 1),
                   slope_coeff = c(0.05, 0.03, 0.051, 0.030, 0.025, 0.025, 0.034),
                   slope_int = c(75.76, 79.52, 81.80, 92.71, 75.76, 72.07, 90.6),                               
                   adjr2 = c(0.87, 0.79, 0.65, 0.89, 0.20, 0.57, 0.90))


acci_bud$Year <- as.factor(acci_bud$Year)
acci_elev_slope$year <- as.factor(acci_elev_slope$year)

g <- ggplot(acci_bud, aes(x = Elevation, y = DOY, color = Year)) + 
       geom_errorbar(aes(ymin = DOY -se, ymax = DOY +se), width = 0.1, show.legend = F)
g <- g + geom_point()
g <- g + geom_abline(data = acci_elev_slope, 
                     aes(slope = slope_coeff, intercept = slope_int, color = year), 
                     linetype = 'dashed', show.legend = F)
g

【问题讨论】:

标签: r ggplot2


【解决方案1】:

您可以通过向点层添加一个假的fill 图例并在geom_abline 中使用show.legend = TRUE 来实现此目的。然后,您可以跳过箍来设置新图例的标题/标签,设置在两个图例中使用的颜色,然后通过 override.aes in guide_legend 覆盖图例的外观。

ggplot(acci_bud, aes(x = Elevation, y = DOY, color = Year)) + 
    geom_errorbar(aes(ymin = DOY -se, ymax = DOY +se), width = 0.1, show.legend = FALSE) + 
    geom_point(aes(fill = Year)) + 
    geom_abline(data = acci_elev_slope, 
              aes(slope = slope_coeff, intercept = slope_int, 
                  color = year), linetype = "dashed", show.legend = TRUE) +
    scale_fill_discrete(name = "slopes", labels = acci_elev_slope$slope_coeff) +
    scale_color_manual(values = rainbow(length(unique(acci_bud$Year)))) +
    guides(color = guide_legend(override.aes = list(linetype = 0)),
          fill = guide_legend(override.aes = list(shape = NA, 
                                            color = rainbow(length(unique(acci_bud$Year))))))

【讨论】:

  • 是否可以将线条全部设为一种类型?我喜欢它们在传说中的虚线,但我似乎对覆盖的理解不足以让情节上的所有线条都被虚线。
  • 您可以使用 fill 而不是 linetype
猜你喜欢
  • 2016-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-23
  • 2018-08-02
  • 1970-01-01
  • 2018-05-11
相关资源
最近更新 更多