问题描述
我想使用R绘制两个变量之间的线性关系,但我希望拟合线仅出现在数据范围内.
Using R, I would like to plot a linear relationship between two variables, but I would like the fitted line to be present only within the range of the data.
例如,如果我有以下代码,我希望该行仅存在于1:10的x和y值(使用默认参数,该行超出了数据点的范围).
For example, if I have the following code, I would like the line to exist only from x and y values of 1:10 (with default parameters this line extends beyond the range of data points).
x <- 1:10
y <- 1:10
plot(x,y)
abline(lm(y~x))
推荐答案
(a)保存拟合模型,而不是使用abline()
,(b)使用predict.lm()
查找与x =对应的拟合y值. 1并且x = 10,然后(c)使用lines()
在两点之间添加一条线:
Instead of using abline()
, (a) save the fitted model, (b) use predict.lm()
to find the fitted y-values corresponding to x=1 and x=10, and then (c) use lines()
to add a line between the two points:
f <- lm(y~x)
X <- c(1, 10)
Y <- predict(f, newdata=data.frame(x=X))
plot(x,y)
lines(x=X, y=Y)
这篇关于在一定范围R内绘制拟合线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!