How to Set Axis Limits in ggplot2?
How to Set Axis Limits in ggplot2?, ggplot2 can frequently be used to set the axis bounds on a plot. The following functions make it simple to accomplish this:
xlim(): defines the x-axis’s lowest and upper limits.
ylim(): defines the y-axis’s lower and upper limits.
Keep in mind that both of these approaches will eliminate data that is outside of the restrictions, which occasionally has unforeseen results.
Use coord_cartesian() instead to alter the axis bounds without losing data observations.
The coord_cartesian() function provides the x- and y-axis bounds without removing observations.
How to Set Axis Limits in ggplot2
Using the scatterplot below, which was created using the built-in R dataset mtcars, this tutorial demonstrates various uses for these functions.
Let’s load the library ggplot2
library(ggplot2)
Now we can create a simple scatterplot
ggplot(mtcars, aes(mpg, wt)) + geom_point()
Example 1: Set X-Axis Limits Using xlim()
Using the xlim() method, the scatterplot’s x-axis boundaries can be defined as seen in the following code:
make a scatterplot with an x-axis of 10 to 40.
ggplot(mtcars, aes(mpg, wt)) + geom_point() + xlim(10, 40)
Additionally, you can use NA to merely provide the upper limit of the x-axis and let ggplot2 determine the lower limit for you.
Now we can create a scatterplot with x-axis upper limit at 40
ggplot(mtcars, aes(mpg, wt)) + geom_point() + xlim(NA, 40)
Example 2: Set Y-Axis Limits Using ylim()
Using the ylim() method, the scatterplot’s y-axis boundaries can be defined as seen in the following code.
make a scatterplot using a 2 to 4 y-axis.
ggplot(mtcars, aes(mpg, wt)) + geom_point() + ylim(2, 4)
Warning message: Removed 8 rows containing missing values (geom_point).
Now let’s try to create a scatterplot with y-axis lower limit at 2
ggplot(mtcars, aes(mpg, wt)) + geom_point() + xlim(2, NA)
Example 3: Set Axis Limits Using coord_cartesian()
The coord_cartesian() method is used to set the scatterplot’s y-axis bounds as shown in the following code.
generate a scatterplot with a 2–4 y-axis.
ggplot(mtcars, aes(mpg, wt)) + geom_point() + coord_cartesian(xlim =c(10, 30), ylim = c(2, 4))