James
James

Reputation: 729

how to define graphical bounds of abline linear regression in R

I am trying to truncate the ends of an abline, which is actually just a linear regression of my data.

fit1=lm(logy~logx)

> fit1

Call:
lm(formula = logy ~ logx)

Coefficients:
(Intercept)         logx  
     -5.339       -2.115 

Where logx is log10(x[1:365] transformed. logy follows the same code. When I plot with abline(fit1,col="red"), I get the line I wanted, but the line extends past the bounds I have originally set [1:365]. I have tried par=xpd and that doesn't reduce the line to the limits I want. I've played around with segments() to no avail. Maybe it is a line() argument?

edit Here is the new solution:

#the following vectors x and y store our data that we want to plot
x<-(1:10)
y<-(10:1)
plot(x,y,type="l",log="xy")
#we want to do a linear regression on our log10 transformed data and add the line to the plot
logy=log10(y[3:8])
logx=log10(x[3:8])
fit1=lm(logy~logx)
#finally, we want the regression line to only seem like it applies over the range from 3 to 8
clip(3,8,8,3)
abline(fit1,col="red")

what this yields is a plot with a line that (now, does not) extends past 3 to 8 on our x-axis. I only want the regression line to display from x=3 to x=8, following the same slope.

Upvotes: 2

Views: 8006

Answers (2)

Rodolfo Souza
Rodolfo Souza

Reputation: 41

You can use segments()

For example:

segments(x0=3, # Value from x (initial)
         x1=8, # Value to x (final)
         y0=5, # Value from y (initial)
         y1=5, # Value to y (final)
         col='red')

Upvotes: 3

Jealie
Jealie

Reputation: 6277

You can clip the drawing area. I can not use your data as your example is not reproducible, but here is an illustration:

> plot(1,1,type='n',xlim=c(0,400), ylim=c(0,10))
> clip(1,365,0,10)
> abline(h=5,col='red')

Results in a line that is bounded inside the box of coordinates x0=1,x1=365,y0=0,y1=10:

enter image description here

Upvotes: 8

Related Questions