Tunc Jamgocyan
Tunc Jamgocyan

Reputation: 331

How to plot the value of abline in R?

I used this code to make this plot:

plot(p, cv2,col=rgb(0,100,0,50,maxColorValue=255),pch=16, 
     panel.last=abline(h=67,v=1.89, lty=1,lwd=3))

My plot looks like this: Plot

1.) How can I plot the value of the ablines in a simple plot?

2.) How can I scale my plot so that both lines appear in the middle?

Upvotes: 5

Views: 23288

Answers (2)

user1317221_G
user1317221_G

Reputation: 15441

to change scale of plot so lines are in the middle change the axes i.e.

x<-1:10
y<-1:10
plot(x,y)
abline(a=1,b=0,v=1)

changed to:

x<-1:10
y<-1:10
plot(x,y,xlim=c(-30,30))
abline(a=1,b=0,v=1)

by "value" I am assuming you mean where the line cuts the x-axis? Something like text? i.e.:

text((0), min(y), "number", pos=2) 

if you want the label on the x axis then try:

abline(a=1,b=0,v=1)
axis(1, at=1,labels=1)

to prevent overlap between labels you could remove the zero i.e.:

plot(x,y,xlim=c(-30,30),yaxt="n")
axis(2, at=c(1.77,5,10,15,20,25))

or before you plot extend the margins and add the labels further from the axis

par(mar = c(6.5, 6.5, 6.5, 6.5))
plot(x,y,xlim=c(-30,30))
abline(a=1,b=0,v=1)
axis(2, at=1.77,labels=1.77,mgp = c(10, 2, 0))

Upvotes: 7

Matthieu Dubois
Matthieu Dubois

Reputation: 327

Similar in spirit to the answer proposed by @user1317221, here is my suggestion

# generate some fake points
x <- rnorm(100)
y <- rnorm(100)

# positions of the lines
vert = 0.5
horiz = 1.3

To display the lines at the center of the plot, first compute the horizontal and vertical distances between the data points and the lines, then adjust the limits adequately.

# compute the limits, in order for the lines to be centered
# REM we add a small fraction (here 10%) to leave some empty space, 
# available to plot the values inside the frame (useful for one the solutions, see below)
xlim = vert + c(-1.1, 1.1) * max(abs(x-vert))
ylim = horiz + c(-1.1, 1.1) * max(abs(y-horiz))

# do the main plotting
plot(x, y, xlim=xlim, ylim=ylim)
abline(h=horiz, v=vert)

Now, you could plot the 'values of the lines', either on the axes (the lineparameter allows you to control for possible overlapping):

mtext(c(vert, horiz), side=c(1,2))

or alternatively within the plotting frame:

text(x=vert, y=ylim[1], labels=vert, adj=c(1.1,1), col='blue')
text(x=xlim[1], y=horiz, labels=horiz, adj=c(0.9,-0.1), col='blue')

HTH

Upvotes: 0

Related Questions