5

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!

agamesh
  • 559
  • 1
  • 10
  • 26
HEnav
  • 133
  • 1
  • 3
  • 7
  • 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
  • 1
    now 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 Answers2

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

x-axis on 0 line

But personally I think that you should use grid() or Andrie solution.

Community
  • 1
  • 1
Marek
  • 49,472
  • 15
  • 99
  • 121
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)

enter image description here

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)

enter image description here

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