【问题标题】:Adding a custom legend to a blank ggplot2 line graph将自定义图例添加到空白 ggplot2 折线图
【发布时间】:2016-10-05 00:06:15
【问题描述】:

我正在尝试为纵向数据集中不同群体的原型个体创建一个固定效应的 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")

我需要知道如何在该图中添加自定义图例来解释线条。理想情况下,我希望将图例放置在相同的位置,并使用与使用基本图形包创建的下图相似的标签。 (注意:我尝试在每个 abline 函数中添加show.legend = TRUE,但没有成功。

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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

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

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

    【讨论】:

    • 感谢@Roman Lustrik。这是一个优雅的解决方案。但是,我仍然想知道在基本图形图中是否存在与 legend() 调用等效的 ggplot2。
    • @llewmills 据我所知,没有。
    猜你喜欢
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    相关资源
    最近更新 更多