Date Range as ggplot2 Plot Axis Limits in R (Example Code)

In this post you’ll learn how to use dates as the limits of a ggplot2 plot axis scale in R programming.

Preparing the Example

set.seed(589673)
my_df <- data.frame(dates = seq(as.Date("2025-05-10"),  # Construct example data
                            by = "day",
                            length.out = 6),
                    values = rnorm(6))
my_df                                                   # Display example data in RStudio console
#        dates     values
# 1 2025-05-10  0.9753311
# 2 2025-05-11 -0.5530573
# 3 2025-05-12  0.1372695
# 4 2025-05-13 -1.4207424
# 5 2025-05-14 -0.8352222
# 6 2025-05-15  0.1896417
install.packages("ggplot2")                             # Install ggplot2 package
library("ggplot2")                                      # Load ggplot2
my_plot <- ggplot(my_df,                                # Draw plot with default axes
                  aes(x = dates,
                      y = values)) +
  geom_line()
my_plot

r graph figure 1 date range as ggplot2 axis limits r

Example: Specify the Limits of a ggplot2 Axis Using Dates

install.packages("scales")                              # Install & load scales package
library("scales")
my_plot +                                               # Define axis limits
  scale_x_date(limits = as.Date(c("2025-05-11", "2025-05-14")))

r graph figure 2 date range as ggplot2 axis limits r

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top