基于geom_smooth的ggplot中的不同颜色 [英] Different colours in ggplot based on geom_smooth
问题描述
我创建了一个线性 geom_smooth
的ggplot,现在我想从 geom_point
拥有点数在线性平滑线以下和以上的颜色不同。
我知道我可以通过做 geom_point(aes(x, y,color = z))
。我的问题是如何确定一个点是否低于或高于线性线。
可以 ggplot2
这样做还是必须先在数据框中创建一个新的列?
以下是带有 geom_smooth
但没有不同的颜色在线以上和以下。
任何帮助表示赞赏。
library(ggplot2)
df< - data.frame(x = rnorm(100),
y = rnorm(100))
ggplot(df,aes(x,y))+
geom_point()+
geom_smooth(method =lm)
我相信ggplot2无法为您做到这一点。正如你所说,你可以在 df
中创建一个新变量来进行着色。你可以这样做,基于线性模型的残差。
例如:
library(ggplot2)
set.seed(2015)
df < - data.frame(x = rnorm(100),
y = rnorm 100))
#拟合线性回归
l = lm(y〜x,data = df)
#根据残差
创建新的组变量df $ group = NA
df $ group [which(l $ residuals> = 0)] =above
df $ group [which(l $ residuals <0)] =below
$ b $#绘制图
ggplot(df,aes(x,y))+
geom_point(aes(color = group))+
geom_smooth(method = lm)
注意颜色
参数必须传递给 geom_point()
,否则 geom_smooth()
会分别适合每个组。 / p>
结果:
I created a ggplot with linear geom_smooth
now i would like to have the points, from the geom_point
to have a different colour below and above the linear smooth line.
I know I can add the color to the point by doing geom_point(aes(x, y, colour = z))
. My problem is how to determine if a point in the plot is below or above the linear line.
Can ggplot2
do this or do have to create a new column in the data frame first?
Below is the sample code with geom_smooth
but without the different colours above and below the line.
Any help is appreciated.
library(ggplot2)
df <- data.frame(x = rnorm(100),
y = rnorm(100))
ggplot(df, aes(x,y)) +
geom_point() +
geom_smooth(method = "lm")
I believe ggplot2 can't do this for you. As you say, you could create a new variable in df
to make the colouring. You can do so, based on the residuals of the linear model.
For example:
library(ggplot2)
set.seed(2015)
df <- data.frame(x = rnorm(100),
y = rnorm(100))
# Fit linear regression
l = lm(y ~ x, data = df)
# Make new group variable based on residuals
df$group = NA
df$group[which(l$residuals >= 0)] = "above"
df$group[which(l$residuals < 0)] = "below"
# Make the plot
ggplot(df, aes(x,y)) +
geom_point(aes(colour = group)) +
geom_smooth(method = "lm")
Note that the colour
argument has to be passed to geom_point()
, otherwise geom_smooth()
will produce a fit to each group separately.
Result:
这篇关于基于geom_smooth的ggplot中的不同颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!