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

标签 r ggplot2

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

最佳答案

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

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

关于r - 将自定义图例添加到空白 ggplot2 线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37639523/

相关文章:

html - 使用 htmlOutput 在 Shiny 的应用程序中将矢量渲染为逗号分隔的文本

RStudio:git add --all 来自 UI

r - 使用 ggplot2 如何表示图例中的点和线

r - 在ggplot图例中更改线型

r - 提取 RColorBrewer 调色板用于其他用途

使用多个数据帧从图中的 ggplot 图例中删除不正确的彩色轮廓?

r - Shiny 的应用程序 rglwidget 让 userMatrix 生成另一个具有相同旋转的图

r - Linux 中的 R 有哪些可用的 IDE?

r - 向量化包含循环和 if 子句的搜索函数

ggplot2 - 不使用 ggpaired 连接观察(点和线)