16

I want to add a diagonal line to the plot. It is not a linear regression line. I just want a diagnol line. Can anyone help me with this? Thanks a lot!

Junhua Zhao
  • 161
  • 1
  • 1
  • 3

8 Answers8

15

If you want to add the 1:1 diagonal line:

qplot(1,1) + geom_abline(intercept = 0, slope = 1)
Lennert
  • 964
  • 10
  • 16
14

You could use abline()

abline(coef = c(0,1))

this gives you a line from intercept 0 with slope 1 in an existing plot.

If you want the line to be diagonal to any plot just set the intercept to the lower left corner and the slope to the ratio of increase between the two axis.

Peter Hartog
  • 141
  • 1
  • 3
10
lines(x = c(0,100), y = c(0,100))
kilojoules
  • 9,768
  • 18
  • 77
  • 149
2

Maybe this is a bit late however, I want to share my answer with you -maybe useful. First, define a panel function and within that define your abline parameters; like below:

require(hexbin)
y=runif(100)
x=runif(100)

panel <- function(x,y, ...){
panel.xyplot(x, y, ...)
panel.abline(0,1, col="red", size = 0.25, lwd = 2)
}

You can customize parameters based on your use-case.

Then you can add "panel" function into your plotting library i.e., ggplot or hexbin plot family. Here I use hexbinplot function which is a very nice function for visualization:

hexbinplot(x ~ y, panel = panel)

Below is how it looks like (remember you can make it much nicer by customizing graphical elements). enter image description here

Sheykhmousa
  • 139
  • 9
0

If you don't want your line to extend through the entire plot range, or if you want to add arbitrary line segments, use segments. For example, the following code will draw a square:

plot.new()
plot.window(xlim = c(0, 3), ylim = c(0, 3))
segments(x0=c(1,1,2,2), x1=c(1,2,2,1), y0=c(1,2,2,1), y1=c(2,2,1,1))
mmuurr
  • 1,310
  • 1
  • 11
  • 21
0

this adds a diagonal line to a ggplot,

qplot(1,1) + annotation_custom(linesGrob(c(0,1), c(0,1)))

or equivalently,

qplot(1,1) + annotate("segment", x=-Inf, xend=Inf,y=-Inf, yend=Inf)
baptiste
  • 75,767
  • 19
  • 198
  • 294
0

A diagonal one, from 0 to 100, for example to show actual vs predicted values: abline=c(0,1)

-2

To add a line, for example, from x=-3, y=-3 to x=3, y=3:

segments(-3,-3,3,3)

Matin Kh
  • 5,192
  • 6
  • 53
  • 77
Kimmo
  • 1