How to Set Axis Limits in ggplot2?

[This article was first published on Methods – finnstats, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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))

How to Make Boxplot in R-Quick Start Guide »

The post How to Set Axis Limits in ggplot2? appeared first on finnstats.

To leave a comment for the author, please follow the link and comment on their blog: Methods – finnstats.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)