R 向ggplot2图形添加第二个图例-数据点和回归线

R 向ggplot2图形添加第二个图例-数据点和回归线,r,ggplot2,R,Ggplot2,我试图为两个数据系列创建两个单独的图例。基本上,我有一个数据系列和回归线,我想要一个带有回归数据的图例,最好是带有报告的adjr2,另一个带有数据集中的点的图例。我是ggplot2的新手,但我还不能理解指南(指南\图例) 这是我的密码。我已经设法得到了图例上要显示的点,所以我想为虚线回归线创建第二个点。我有一列用于调整后的r2值,我想为第二个图例调用该列 g <- ggplot(acci_bud, aes(x = Elevation, y = DOY, color = Year)) +

我试图为两个数据系列创建两个单独的图例。基本上,我有一个数据系列和回归线,我想要一个带有回归数据的图例,最好是带有报告的adjr2,另一个带有数据集中的点的图例。我是ggplot2的新手,但我还不能理解指南(指南\图例)

这是我的密码。我已经设法得到了图例上要显示的点,所以我想为虚线回归线创建第二个点。我有一列用于调整后的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)

g您可以通过向点图层添加一个假的
fill
图例,并在
geom\u abline
中使用
show.legend=TRUE
来实现这一点。然后,您可以通过跳转设置新图例的标题/标签,设置两个图例中使用的颜色,然后通过
guide\u legend
中的
override.aes
覆盖图例的外观

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
图例,并在
geom\u abline
中使用
show.legend=TRUE
来实现这一点。然后,您可以通过跳转设置新图例的标题/标签,设置两个图例中使用的颜色,然后通过
guide\u legend
中的
override.aes
覆盖图例的外观

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

提供一些内置数据集的可复制示例。提供一些内置数据集的可复制示例。有可能把所有的线都做成一种类型吗?我喜欢它们在图例中是虚线,但我似乎不太了解覆盖,无法使绘图上的所有线条都是虚线。您可以使用
填充
而不是
线型
。是否可以使线条都是一种类型?我喜欢它们在图例中是虚线,但我似乎不太了解覆盖,无法使绘图上的所有线条都是虚线。您可以使用
填充
而不是
线型