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!
If we want to change the position of X-axis in base R plot then we can use axis function with pos argument. The pos argument will decide the position of the X-axis on Y-axis.
To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.
You can create custom axes using the axis( ) function. axis(side, at=, labels=, pos=, lty=, col=, las=, tck=, ...) the coordinate at which the axis line is to be drawn. If you are going to create a custom axis, you should suppress the axis automatically generated by your high level plotting function.
Adding axis to a Plot in R programming – axis () Function axis() function in R Language is to add axis to a plot. It takes side of the plot where axis is to be drawn as argument. Parameters: side: It defines the side of the plot the axis is to be drawn on possible values such as below, left, above, and right.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With