2014-10-01 120 views
2

我已经设法在一个绘图上创建了具有两个数据集的散点图。一组数据的X轴范围从0到40(绿色),而另一组数据范围从0到15(红色)。在R中设置趋势线长度

(http://s9.postimg.org/fw48s8rq7/Rplot.jpg)

我用这个代码来添加趋势线分开(使用参数(新))的红色和绿色数据。

plot(x1,y1, col="red", axes=FALSE, xlab="",ylab="",ylim= range(0:1), xlim= range(0:40)) 
f <- function(x1,a,b,d) {(a*x1^2) + (b*x1) + d} 
fit <- nls(y1 ~ f(x1,a,b,d), start = c(a=1, b=1, d=1)) 
co <- coef(fit) 
curve(f(x, a=co[1], b=co[2], d=co[3]), add = TRUE, col="red", lwd=1) 

我的问题是我似乎无法找到一种方法来停止X轴上的红色趋势线15。我“搜索了”周围,似乎没有出现我的问题。超越趋势线!我厌倦了添加一个end =语句以适合< - 而且这也没有效果。

请帮忙,

我希望我已经发布了足够的信息。提前致谢。

+0

谢谢@nograpes。由于缺乏经验值,我无法发布照片。 – User67539586 2014-10-01 16:49:53

回答

0

您可以在基地图形与curve功能的fromto参数做到这一点(见curve帮助了解详细信息)。例如:

# Your function 
f <- function(x1,a,b,d) {(a*x1^2) + (b*x1) + d} 

# Plot the function from x=-100 to x=100 
curve(f(x, a=-2, b=3, d=0), from=-100, to=100, col="red", lwd=1, lty=1) 

# Same curve going from x=-100 to x=0 (and shifted down by 1000 units so it's 
# easy to see) 
curve(f(x, a=-2, b=3, d=-1000), from=-100, to=0, 
     add=TRUE, col="blue", lwd=2, lty=1) 

enter image description here

如果你想以编程方式设置曲线X-限制,你可以做这样的事情(假设你的数据帧被称为df和你的x变量称为x) :

curve(f(x, a=-2, b=3, d=0), from=range(df$x)[1], to=range(df$x)[2], 
     add=TRUE, col="red", lwd=1, lty=1) 
+0

完美!谢谢! – User67539586 2014-10-01 20:48:32

1

尝试使用ggplot。下面的示例使用mtcars数据:

library(ggplot2) 
ggplot(mtcars, aes(qsec, wt, color=factor(vs)))+geom_point()+ stat_smooth(se=F) 

enter image description here

+1

我想你可以只做'geom_smooth(se = FALSE)'而不是两个'stat_smooth'调用。 – eipi10 2014-10-01 17:05:53

+0

感谢您的建议。我早些时候尝试过,但它不起作用,因为那时我正在使用color = vs而不是color = factor(vs) – rnso 2014-10-01 17:16:34

+0

也很好理解。感谢您的答复。我还没有完全掌握ggplot,所有其他图形都与上述格式相同。 – User67539586 2014-10-01 20:49:42