In this recipe, we will learn how to adjust the X and Y limits of plots, which is useful in adjusting a graph to suit one's presentation needs and adding additional data to the same plot.
We will modify our first scatter plot example to demonstrate how to adjust axes limits:
plot(cars$dist~cars$speed, xlim=c(0,30), ylim=c(0,150))
In our original scatter plot in the first recipe of this chapter, the x axis limits were set to just below 5 and up to 25 and the y axis limits were set from 0 to 120. In this example, we set the x axis limit to 0 to 30 and y axis limits to 0 to 150 using the xlim
and ylim
arguments respectively.
Both xlim
and ylim
take a vector of length 2 as valid values in the form c(minimum,maximum)
that is, xlim=c(0,30)
means set the x axis minimum limit to 0 and maximum limit to 30.
You may have noticed that even after setting the x and y limit values, there is some gap left at either edges. The two axes zeroes don't coincide. This is because R automatically adds some additional space at both the edges of the axes, so that if there are any data points at the extremes, they are not cut off by the axes. If you wish to set the axes limits to exact values, in addition to specifying xlim
and ylim
, you must also set the xaxs
and yaxs
arguments to "i"
:
plot(cars$dist~cars$speed, xlim=c(0,30), ylim=c(0,150), xaxs="i", yaxs="i")
Sometimes, we may wish to reverse a data axis, say to plot the data in descending order along one axis. All we have to do is swap the minimum and maximum values in the vector argument supplied as xlim
or ylim
. So, if we want the X axis speed values in the previous graph in descending order we need to set xlim
to c(30,0)
:
plot(cars$dist~cars$speed, xlim=c(30,0), ylim=c(0,150), xaxs="i", yaxs="i")
There will be a few more recipes on adjusting the axes tick marks and labels in Chapter 2, Beyond the Basics.