# scatter plot - Setting Trend Line Length in R

I have managed to create a scatterplot with two datasets on a single plot. One set of data has an X axis that ranges from 0 -40 (Green), while the other only ranges from 0 -15 (Red).

I used this code to add trend lines to the red and green data separately (using par(new)).

``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)``

My issue is I can't seem to find a way to stop the red trend line at 15 on the x axis. I "googled" around and nothing seemed to come up for my issue. Lots on excel trend lines! I tired adding an end= statement to fit<- and that did not work either.

I hope I have posted enough information. Thanks in advance.

You can do this in base graphics with the `from` and `to` arguments of the `curve` function (see the help for `curve` for more details). For example:

``````# 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)
``````

If you want to set the curve x-limits programmatically, you can do something like this (assuming your data frame is called `df` and your x-variable is called `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)
``````

Try using ggplot. Following example uses mtcars data:

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