我有50个温度和湿度数据点,我想在geom_point上绘制,并为我的ggplot
添加一个线性模型。但是,我无法这样做。我尝试过abline
,geom_line
,geom_smooth
和lm
。
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
?任何帮助表示赞赏。谢谢。我怎样才能在图上区分温度和湿度点?
这就是我目前所拥有的^
正如评论部分所述,你在+
之后错过了一个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)
你需要为x
和y
提供“美学”,否则你会得到以下错误:
错误:stat_smooth需要以下缺失的美学:x,y
method = "lm"
告诉geom_smooth
您想要使用线性模型方法,而formula
指定要绘制的模型公式。如果我们没有指定method
,geom_smooth
默认为“loess”(如@Lyngbakr所述)并给出警告消息:
geom_smooth()
使用method ='loess'和公式'y~x'
由于我们必须在geom_point
和geom_smooth
提供相同的美学,更方便的方法是写:
ggplot(iris, aes(x = Petal.Length , y = Petal.Width)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ x)
输出:
为了回答OP的第二个问题“我怎样才能根据颜色区分温度和湿度点?”,我们可以将color
和size
美学添加到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
(圆圈的“情节字符”)来包裹每个点。这给出了一个分隔每个点的漂亮边框。
输出: