How to Set Axis Limits in ggplot2?
How to Set Axis Limits in ggplot2?
Setting the axis bounds on a plot using ggplot2 is a common task. Using the following functions, you can accomplish so quickly.
xlim(): specifies the lower and upper limit of the x-axis. ylim(): specifies the lower and upper limit of the y-axis.
Both of these approaches will eliminate data that is outside of the bounds, which can have unforeseen implications.
Transition plot in R-change in time visualization »
You can use coord_cartesian() instead to modify the axis bounds without losing data observations
How to Set Axis Limits in ggplot2?
Let’s start by loading the library and a simple plot.
How to find z score in R-Easy Calculation-Quick Guide »
library(ggplot2) p <- ggplot(ToothGrowth, aes(x = factor(dose), y = len,fill=factor(dose))) + geom_boxplot() p
Approach 1: Set X-Axis Limits Using xlim()
The following code demonstrates how to use the xlim() function to set the scatterplot’s x-axis limits.
create a scatterplot with x-axis ranging from 0 to 5
Point Biserial Correlation in R-Quick Guide »
p + xlim(0, 5)
Approach 2: Set Y-Axis Limits Using ylim()
The following code demonstrates how to use the ylim() function to set the scatterplot’s y-axis limits:
create a scatterplot with a y-axis ranging from 0 to 45
How to perform ANCOVA in R » Quick Guide »
p + ylim(0, 45)
Approach 3: Set Axis Limits Using coord_cartesian()
Using the coord_cartesian() function, the following code explains how to specify the scatterplot’s y-axis limits.
create a scatterplot with a y-axis ranging from 0 to 50 and an x-axis from 0 to 3.
p+ coord_cartesian(xlim =c(0, 3), ylim = c(0, 50))