2017-02-04 112 views
1

我想要为两个数据系列创建两个单独的图例。基本上我有一个数据序列和回归线,并且我想要一个带有回归数据的图例,最好带有adjr2报告,另一个图例带有来自数据集的点。我是ggplot2的新手,我一直无法弄清楚指南(guide_legend)。向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) 

plot I've managed to make, minus the second legend

我可以使这个情节与基础包,但我希望能有我使用的多个数据集,我觉得GGPLOT2更有利于这种基本的脚本。

base package plot, goal is something similar to this using 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 
+2

为一些内置数据集提供可重现的示例。 http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Koundy

回答

0

您可以通过添加一个假fill传奇点层和geom_abline使用show.legend = TRUE实现这一目标。然后你可以跳过这个圈子来设置新图例的标题/标签,设置两个图例中使用的颜色,然后重写override.aesguide_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)))))) 
+0

美丽!非常感谢,完美的工作。 – sarahw

+0

是否可以将线条全部设为一种类型?我喜欢它们在传奇中破灭,但我似乎并没有理解这种重叠,足以让剧情中的所有线条都被打破。 – sarahw

+0

您可以使用'fill'而不是'linetype'来利用事物。 – aosmith