0

I am making a time series figure in ggplot2 and would like to set limits for the x-axis. When I try to set the limits using scale_x_datetime(limits = ...), dates beyond the limits are shown, how can I avoid this? I have tried using answers found in similar SO questions (similar 1, similar 2) but have not had success.

Example Data:

library(ggplot2)
library(lubridate)

df <- data.frame(matrix(ncol = 2, nrow = 70176))
colnames(df)[1:2] <- c("DateTime","Value")
df$DateTime <- seq(ymd_hm('2020-01-01 00:00'),ymd_hm('2021-12-31 23:45'), by = '15 mins')
df$Value <- rnorm(70176,100,20)

This attempt comes from the first similar SO question

lims <- as.POSIXct(strptime(c("2020-01-01 00:00","2021-12-31 23:45"), format = "%Y-%m-%d %H:%M"))    

ggplot(df, aes(x = DateTime, y = Value)) +
  geom_line() +
  scale_x_datetime(date_labels = "%b %d %Y",
                   date_breaks = "1 month",
                   limits = lims) +
  labs(x = "",
       y = "Value") +
  theme_bw() +
  theme(panel.grid = element_blank(),
        text = element_text(size = 16, color = "black"),
        axis.text.x = element_text(size = 16, color = "black", angle = 90, vjust = 0.5, hjust = 1),
        axis.text.y = element_text(size = 16, color = 'black'))

This attempt comes from the second similar SO question

ggplot(df, aes(x = DateTime, y = Value)) +
  geom_line() +
  scale_x_datetime(date_labels = "%b %d %Y",
                   date_breaks = "1 month",
                   limits = c(min(df$DateTime), max(df$DateTime))) +
  labs(x = "",
       y = "Value") +
  theme_bw() +
  theme(panel.grid = element_blank(),
        text = element_text(size = 16, color = "black"),
        axis.text.x = element_text(size = 16, color = "black", angle = 90, vjust = 0.5, hjust = 1),
        axis.text.y = element_text(size = 16, color = 'black'))

The ideal figure would not display dates outside of the limits of the data (i.e., Dec 2019 or Jan 2022).

tassones
  • 891
  • 5
  • 18

2 Answers2

0

@JonSpring suggestion of using scale_x_datetime(..., expand = expansion(add = c(0,0))) answered my question. Below is the code using the example dataset for others who might come across this question.

lims <- as.POSIXct(strptime(c("2019-12-15 00:00","2022-01-15 23:45"), format = "%Y-%m-%d %H:%M"))    

ggplot(df, aes(x = DateTime, y = Value)) +
  geom_line() +
  scale_x_datetime(date_labels = "%b %d %Y",
                   date_breaks = "1 month",
                   limits = lims,
                   expand = expansion(add = c(0,0))) +
  labs(x = "",
       y = "Value") +
  theme_bw() +
  theme(panel.grid = element_blank(),
        text = element_text(size = 16, color = "black"),
        axis.text.x = element_text(size = 16, color = "black", angle = 90, vjust = 0.5, hjust = 1),
        axis.text.y = element_text(size = 16, color = 'black'))
tassones
  • 891
  • 5
  • 18
0

Using expand = c(0,0) in scale_x_datetime() will remove extra space.

Nitesh Shriwash
  • 128
  • 1
  • 6