I'm trying to create a simple scatter plot in R, where the x-axis range is -10:10, and to re-locate the y axis to the x=0 point. This seems like a fairly basic operation, but I found no way to do that... Thanks for any help!
Asked
Active
Viewed 1.1k times
5
-
Argument to define x axis range is `plot(..., xlim = c(-10, 10))`. See `?par` for more info. – Roman Luštrik Jun 17 '11 at 10:00
-
1now why would you want to do this and have an axis and it's labels drawn over your data? This is one of the reasons I hate Excel's plotting - it is just a silly thing to do. A grid behind the data would be far better. – Gavin Simpson Jun 17 '11 at 12:38
2 Answers
7
x <- runif(50, -10, 10)
y <- runif(50, -10, 10)
plot(x, y, yaxt="n") # don't plot y-axis, see ?par, section xaxt
axis(2, pos=0) # Draw y-axis at 0 line
But personally I think that you should use grid()
or Andrie solution.
-
3+1 for answering the question as written. I might suggest `las=1` as well (and maybe `bty="n"`) – Ben Bolker Jun 17 '11 at 11:57
3
Create some data
x <- runif(50, -10, 10)
y <- runif(50, -10, 10)
In base graphics, you can use the abline
function to draw lines on a plot. The trick is to draw a vertical line and horizontal line at the x=0
and y=0
positions:
plot(x, y)
abline(h=0)
abline(v=0)
An alternative way of achieving a similar result is to use the ggplot2
package:
library(ggplot2)
qplot(x, y) + geom_vline(xintercept=0) + geom_hline(yintercept=0)

Andrie
- 176,377
- 47
- 447
- 496
-
`abline(h=0, v=0)` is a shorthand. Or even one-liner: `plot(x, y, panel.last=abline(h=0,v=0))`. – Marek Jun 17 '11 at 19:03