我用回归线制作了散点图:
ggplot(data = msleep, aes(x = bodywt, y = brainwt, color = bodywt)) +
geom_point() +
geom_smooth(method = 'lm', se = F, aes(color=..y..)) +
labs(title = 'Scatter Plot of Body Weight vs. Brain Weight', x = 'Body Weight', y = 'Brain Weight')
但是,我想更改回归线的颜色,使其遵循与点相同的梯度(基于 bodywt),以便左下角为深蓝色,右上角为浅蓝色。我该怎么做?
一种选择是使用
ggforce::geom_link2
,但这需要手动创建回归线并将拟合值添加到数据集中:
library(ggplot2)
library(ggforce)
msleep$.fitted <- predict(
lm(brainwt ~ bodywt, data = msleep), newdata = msleep
)
ggplot(data = msleep, aes(x = bodywt, y = brainwt, color = bodywt)) +
geom_point() +
geom_link2(
aes(y = .fitted)
) +
labs(
title = "Scatter Plot of Body Weight vs. Brain Weight",
x = "Body Weight",
y = "Brain Weight"
)
#> Warning: Removed 27 rows containing missing values (`geom_point()`).