ggplot2::xlim() and ggplot2::ylim()
   get_help() docs


Description

All functions documented here are part of the {ggplot2} package, which is part of the {tidyverse}.

The {ggplot2} package provides several functions for customizing the limits, aka ranges, of the axes in your {ggplot2} plots, as described below. {ggplot2} will usually pick a reasonable axis range, so using these functions is not necessary unless you need to change the ranges for a specific data visualization goal.

If you also want to customize the specific tickmark (aka “break”) locations on axes, either…

# Load the library
library(ggplot2)
# Or, load the full tidyverse:
library(tidyverse)

# Or, use :: notation, for example with xlim()
ggplot2::xlim() 

Conceptual Usage

# Set x-axis limits with `xlim()`
xlim(low x value, high x value)

# Set x-axis limits with `ylim()`
ylim(low y value, high y value)

Examples

The examples below use the msleep dataset. Learn more about this dataset with get_help("msleep").

# Show the msleep dataset with head()
head(msleep)
## # A tibble: 6 × 11
##   name  genus vore  order conservation sleep_total sleep_rem sleep_cycle awake  brainwt  bodywt
##   <chr> <chr> <chr> <chr> <chr>              <dbl>     <dbl>       <dbl> <dbl>    <dbl>   <dbl>
## 1 Owl … Aotus omni  Prim… <NA>                17         1.8      NA       7    0.0155    0.48 
## 2 Moun… Aplo… herbi Rode… nt                  14.4       2.4      NA       9.6 NA         1.35 
## 3 Grea… Blar… omni  Sori… lc                  14.9       2.3       0.133   9.1  0.00029   0.019
## 4 Cow   Bos   herbi Arti… domesticated         4         0.7       0.667  20    0.423   600    
## 5 Thre… Brad… herbi Pilo… <NA>                14.4       2.2       0.767   9.6 NA         3.85 
## 6 Nort… Call… carni Carn… vu                   8.7       1.4       0.383  15.3 NA        20.5


# This example does NOT set limits, but uses ggplot2's default chosen ranges
# Compare this default to the subsequent examples to see how xlim() and ylim() behave
ggplot(msleep) + 
  aes(x = sleep_rem, y = awake) + 
  geom_point() 


# Set the x-axis limits to range from 0-24, for example
ggplot(msleep) + 
  aes(x = sleep_rem, y = awake) + 
  geom_point() +
  xlim(0, 24)


# Set the y-axis limits to range from 0-40, for example
ggplot(msleep) + 
  aes(x = sleep_rem, y = awake) + 
  geom_point() +
  ylim(0, 40)


# Set both the x- and y-axis limits to range from 0-24
ggplot(msleep) + 
  aes(x = sleep_rem, y = awake) + 
  geom_point() +
  xlim(0, 24) +
  ylim(0, 24)


# CAUTION!! If you limit the ranges too much, data is excluded! See the "Warning" from this code.
# Always make sure you are not excluding data that you don't specifically intend to exclude
ggplot(msleep) + 
  aes(x = sleep_rem, y = awake) + 
  geom_point() +
  # Narrow axis ranges will exclude data:
  xlim(1, 3) +
  ylim(2, 7)
## Warning: Removed 59 rows containing missing values (geom_point).