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!
-
7Have a look at `abline(...)`. – jlhoward Dec 14 '14 at 01:13
-
3or `geom_abline` if you are using ggplot – rawr Dec 14 '14 at 01:15
8 Answers
If you want to add the 1:1 diagonal line:
qplot(1,1) + geom_abline(intercept = 0, slope = 1)

- 964
- 10
- 16
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.

- 141
- 1
- 3
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).

- 139
- 9
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))

- 1,310
- 1
- 11
- 21
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)

- 75,767
- 19
- 198
- 294
A diagonal one, from 0 to 100, for example to show actual vs predicted values: abline=c(0,1)

- 57
- 8