R Set ggplot2 Axis Limits without Deleting Data Rows (2 Examples)
In this R programming post you’ll learn how to set the axis limits of a ggplot2 plot without removing data points.
Preparing the Examples
head(iris) # Iris data set # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
head(iris) # Iris data set # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
install.packages("ggplot2") # Install & load ggplot2 package library("ggplot2") |
install.packages("ggplot2") # Install & load ggplot2 package library("ggplot2")
Example 1: Zoom with Cut-Off
ggplot(iris, aes(Sepal.Length, Sepal.Width, group = Species)) + # Basic plot geom_line() |
ggplot(iris, aes(Sepal.Length, Sepal.Width, group = Species)) + # Basic plot geom_line()
ggplot(iris, aes(Sepal.Length, Sepal.Width, group = Species)) + # Cutting off values geom_line() + xlim(5, 7) + ylim(2, 4.3) # Warning: # Removed 34 rows containing missing values (geom_path). |
ggplot(iris, aes(Sepal.Length, Sepal.Width, group = Species)) + # Cutting off values geom_line() + xlim(5, 7) + ylim(2, 4.3) # Warning: # Removed 34 rows containing missing values (geom_path).
Example 2: Zoom without Cut-Off
ggplot(iris, aes(Sepal.Length, Sepal.Width, group = Species)) + # Not cutting off values geom_line() + coord_cartesian(xlim = c(5, 7), ylim = c(2, 4.3)) |
ggplot(iris, aes(Sepal.Length, Sepal.Width, group = Species)) + # Not cutting off values geom_line() + coord_cartesian(xlim = c(5, 7), ylim = c(2, 4.3))