将自定义图例添加到空白ggplot2折线图

时间:2016-06-05 07:32:44

标签: r ggplot2

我正在尝试为纵向数据集中不同群体的原型个体创建固定效应的ggplot2图表(绘制种族和教育年限对工资增长的影响)。我没有使用数据集本身,而是尝试根据混合效应模型中的截距和斜率系数创建折线图。因此,我创建了一个空白框架并添加了ablines。但是,我想在解释这些线条的情节中添加一个图例。这是我用来创建情节的代码。

df <- data.frame() 
fixef.c <- list(intercept0 = 1.72, slope0 = 0.04, intercept1 = 0.038, slope1 = -0.016) 
ggplot(df) + xlim(0, 12) + ylim(1.6, 2.4) + 
  geom_abline(intercept = fixef.c[[1]], slope = fixef.c[[2]]) +
  geom_abline(intercept = fixef.c[[1]] + fixef.c[[3]]*3, slope = fixef.c[[2]], linetype = 2) +
  geom_abline(intercept = fixef.c[[1]], slope = fixef.c[[2]] + fixef.c[[4]], linetype = 3) +
  geom_abline(intercept = fixef.c[[1]] +  fixef.c[[3]]*3, slope = fixef.c[[4]] + fixef.c[[2]], linetype = 4) +
  xlab("Log Wages") +
  ylab("Years Experience")

我需要知道如何在此图中添加自定义图例来解释这些线条。理想情况下,我希望图例放置在相同的位置,并使用基本图形包创建下面的图表。 (注意:我尝试将show.legend = TRUE添加到每个abline函数中,但它不起作用。

exper.seq <- seq(0, 12)
x.w9 <- fixef.c[[1]] + fixef.c[[2]]*exper.seq
x.w12 <-  fixef.c[[1]] + fixef.c[[2]]*exper.seq + fixef.c[[3]]*3
x.b9 <- fixef.c[[1]] + fixef.c[[2]]*exper.seq + fixef.c[[4]]*exper.seq
x.b12 <- fixef.c[[1]] + fixef.c[[2]]*exper.seq + fixef.c[[3]]*3 + 
         fixef.c[[4]]*exper.seq
plot(exper.seq, x.w9, ylim=c(1.6, 2.4), ylab="LNW.hat", xlab="EXPER", type="l", lwd=2)
lines(exper.seq, x.w12, lty=3)
lines(exper.seq, x.b9, lty=4, lwd=2)
lines(exper.seq, x.b12, lty=5)
legend(0, 2.4, c("9th grade, White/Latino", "9th grade, Black", 
       "12th grade, White/Latino", "12th grade, Black"), lty=c(1, 4, 3, 5))

1 个答案:

答案 0 :(得分:2)

如果您可以承认创建一个包含截距和斜率的对象,以及分组,这是一项相当简单的任务。

xy <- as.data.frame(
  rbind(line1 = c(intercept = fixef.c[[1]], slope = fixef.c[[2]]),
      line2 = c(intercept = fixef.c[[1]] + fixef.c[[3]]*3, slope = fixef.c[[2]]),
      line3 = c(fixef.c[[1]], slope = fixef.c[[2]] + fixef.c[[4]]),
      line4 = c(fixef.c[[1]] +  fixef.c[[3]]*3, slope = fixef.c[[4]] + fixef.c[[2]]))
)
xy$design <- rownames(xy)

ggplot() + 
  xlim(0, 12) + ylim(1.6, 2.4) +
  geom_abline(data = xy, aes(intercept = intercept, slope = slope, linetype = design))

您还可以修改哪个线型属于哪个级别。

scale_linetype_manual(values = c(line1 = "solid", line2 = "dashed", line3 = "dotted", line4 = "dotdash")) +

enter image description here