适合数据

Fit an abline to data

我有 50 个温度和湿度数据点,我想在 geom_point 上绘制并向我的 ggplot 添加一个线性模型。但是,我无法这样做。我试过 ablinegeom_linegeom_smoothlm

temp_humidity_data <- dplyr::select(data, temperature:humidity)

lm(formula = humidity ~ temperature, data = temp_humidity_data)

ggplot(temp_humidity_data) +
geom_point(aes (x = temperature , y = humidity))
geom_smooth()

如何将 lm 添加到我的 `ggplot?任何帮助表示赞赏。谢谢你。我如何通过颜色以及情节来区分温度和湿度点?

这是我目前拥有的^

如评论部分所述,您在 geom_point 后漏了一个 + 符号。除此之外,您还缺少 geom_smooth:

中的一些参数
library(ggplot2)

ggplot(iris) +
  geom_point(aes(x = Petal.Length , y = Petal.Width)) +
  geom_smooth(aes(x = Petal.Length, y = Petal.Width), 
              method = "lm", formula = y ~ x)

您需要为 xy 提供 "aesthetics",否则会出现以下错误:

Error: stat_smooth requires the following missing aesthetics: x, y

method = "lm" 告诉 geom_smooth 您想要使用线性模型方法,而 formula 指定要绘制的模型公式。如果我们不指定 methodgeom_smooth 默认为 "loess"(如@Lyngbakr 所述)并给出警告消息:

geom_smooth() using method = 'loess' and formula 'y ~ x'

因为我们必须在 geom_pointgeom_smooth 中提供相同的美学,更方便的方法是写:

ggplot(iris, aes(x = Petal.Length , y = Petal.Width)) +
  geom_point() +
  geom_smooth(method = "lm", formula = y ~ x)

输出:

为了回答 OP 的第二个问题 "how could i differentiate the temperature and humidity points by colour as well on the plot?",我们可以将 colorsize 美学添加到 geom_point,如下所示:

ggplot(iris, aes(x = Petal.Length , y = Petal.Width)) +
  geom_point(aes(color = Petal.Length, size = Petal.Width)) +
  geom_smooth(method = "lm", formula = y ~ x)

输出:

要更改尺寸和颜色的范围,我们使用 scale_fill_continuous(或 scale_color_continuous 表示 color)和 scale_size_continuous:

ggplot(iris, aes(x = Petal.Length , y = Petal.Width)) +
  geom_point(aes(fill = Petal.Length, size = Petal.Width), pch = 21) +
  geom_smooth(method = "lm", formula = y ~ x) +
  scale_fill_continuous(low = "red", high = "blue") +
  scale_size_continuous(range = c(1, 10))

请注意,当您增加 size 范围时,一些点开始相互重叠。为了减少混淆,我使用 fill 而不是 color 并添加了 pch = 21(一个圆的 "plot character")来环绕每个点。这提供了一个很好的边框来分隔每个点。

输出: