【问题标题】:Linear Regression on Specific Points特定点的线性回归
【发布时间】:2021-06-19 15:43:26
【问题描述】:

如何根据具有相同颜色的彩色点绘制 4 条线性回归线(线也使用相同颜色)?

当前图表:

代码:

注意:

y_tilde = 每天吸的香烟

x_1 = 父亲的年龄

x_2 = 教育年限

print(ggplot(data=df, mapping=aes(y=y_tilde, x=x_1, col=x_2)) 
  + xlab("Father's Age")
  + ylab("Cigarettes Smoked Per Day")
  + labs(color="Years of Education") 
  + geom_point(aes(colour = cut(x_2, breaks=c(-Inf, 10, 12, 14, 16), labels=c(10, 12, 14, 16)))))

【问题讨论】:

  • 事先创建您的cut() 变量(这样您就不必重复代码)和+ geom_smooth(method="lm", aes(colour = cut_var, fill = cut_var)) ?
  • 使用@BenBolker 解决方案 sb 将获得双重图例而无需更新 labs 所以记得也要更新它。

标签: r ggplot2 linear-regression


【解决方案1】:

首先查看?aes 帮助页面。 ggplot(data=df, mapping=aes(y=y_tilde, x=x_1, col=x_2)) 部分不需要在 aes 中指定 col 参数,因为您正在为每个单独的 geom 设置它。

aa <- airquality
aa$cut <- factor(aa$Month)

带有一个全局aes的样本数据示例:

print(ggplot(data = aa, mapping = aes(y = Ozone, x = Temp, col = cut)) +
      xlab("Father's Age") +
      ylab("Cigarettes Smoked Per Day") +
      labs(color = "Years of Education") +
      geom_point() +
      geom_smooth(method = "lm"))

示例数据示例,每个aes 对应一个geom

print(ggplot(data = aa, mapping = aes(y = Ozone, x = Temp)) +
        xlab("Father's Age") +
        ylab("Cigarettes Smoked Per Day") +
        labs(color = "Years of Education") +
        geom_point(aes(col = cut)) +
        geom_smooth(method = "lm", aes(col = cut)))

@BenBolker 指出第二件事是使用 DRY 规则 https://pl.wikipedia.org/wiki/DRY,在绘图定义上定义 cut 变量一次。其他解决方案是使用 cut 变量作为全局 aes,我将定义这样的变量也更清楚。

如果您也想更新回归区间的颜色,请添加到aes 参数fill = cut。我也在这里更改了labs

print(ggplot(data = aa, mapping = aes(y = Ozone, x = Temp)) +
        xlab("Father's Age") +
        ylab("Cigarettes Smoked Per Day") +
        labs(color = "Years of Education", fill = "Years of Education") +
        geom_point(aes(col = cut)) +
        geom_smooth(method = "lm", aes(col = cut, fill = cut)))

【讨论】:

  • 谢谢,我最终使用了全球aesaes 的文档非常糟糕。它甚至没有告诉你它所有可能的参数或col 代表什么。
  • 是的col 是一个棘手的问题,color 或替代colour 的快捷方式也是如此,这三个在使用上没有区别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 2021-01-28
  • 2021-10-12
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
相关资源
最近更新 更多