【问题标题】:ggplot2: one regression line per category [duplicate]ggplot2:每个类别一条回归线[重复]
【发布时间】:2018-11-19 11:46:30
【问题描述】:

根据this ggplot2 tutorial,以下代码生成多色散点图:

library(ggplot2)
gg <- ggplot(midwest, aes(x=area, y=poptotal)) + 
  geom_point(aes(col=state), size=3) +  # Set color to vary based on state categories.
  geom_smooth(method="lm", col="firebrick", size=2) + 
  coord_cartesian(xlim=c(0, 0.1), ylim=c(0, 1000000)) + 
  labs(title="Area Vs Population", subtitle="From midwest dataset", y="Population", x="Area", caption="Midwest Demographics")
plot(gg)

如何制作多条回归线(即每个州一条)?

【问题讨论】:

  • @Hack-R 我不相信这是一个完全的骗局,下面的答案只使用一次调用geom_smooth 来绘制所有回归线。
  • @RuiBarradas 看来 question 是骗人的,但我同意 answer 可能不是。它提出了一个有趣的观点。现在我们应该关闭重复的questions。但是,也许我们关闭的应该是重复的问答对?你可以在 Meta 上问。
  • @Hack-R Done.
  • @wwl 我可以推荐阅读?geom_smooth。在示例中,您会发现“Smoothes 自动适合每个组(由分类美学或组美学定义)”; ggplot(mpg, aes(displ, hwy, colour = class)) + geom_smooth(se = FALSE, method = lm)

标签: r ggplot2 regression


【解决方案1】:

实际上,您已将col=state 属性移至geom_pointaes,这就是geom_smooth 无法使用其(分组)的原因。一种选择是将col=state 移动到aes 本身的ggplot 中。修改后的代码如下:

library(ggplot2)

gg <- ggplot(midwest, aes(x=area, y=poptotal, col=state)) + 
  geom_point(size=3) +  # Set color to vary based on state categories.
  geom_smooth(method="lm", size=1, se=FALSE) + 
  coord_cartesian(xlim=c(0, 0.1), ylim=c(0, 1000000)) + 
  labs(title="Area Vs Population", subtitle="From midwest dataset", y="Population",
  x="Area", caption="Midwest Demographics")
plot(gg)

【讨论】:

    猜你喜欢
    • 2016-03-01
    • 1970-01-01
    • 2012-09-21
    • 2016-01-31
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多