适合数据的abline

问题描述 投票:0回答:1

我有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()

我怎样才能在我的`ggplot中添加lm?任何帮助表示赞赏。谢谢。我怎样才能在图上区分温度和湿度点?

enter image description here

这就是我目前所拥有的^

r ggplot2 lm
1个回答
1
投票

正如评论部分所述,你在+之后错过了一个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提供“美学”,否则你会得到以下错误:

错误:stat_smooth需要以下缺失的美学:x,y

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

geom_smooth()使用method ='loess'和公式'y~x'

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

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

输出:

enter image description here

为了回答OP的第二个问题“我怎样才能根据颜色区分温度和湿度点?”,我们可以将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)

输出:

enter image description here

要更改大小和颜色的范围,我们使用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(圆圈的“情节字符”)来包裹每个点。这给出了一个分隔每个点的漂亮边框。

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.