Skip to content

Instantly share code, notes, and snippets.

@francisbarton
Created January 30, 2024 23:45
Show Gist options
  • Save francisbarton/39fd058e132767a27d2e44825ab2aeb2 to your computer and use it in GitHub Desktop.
Save francisbarton/39fd058e132767a27d2e44825ab2aeb2 to your computer and use it in GitHub Desktop.
ggplot2 labelling reprex
library(ggplot2)
library(lubridate, warn.conflicts = FALSE)
t <- lubridate::as_datetime("2021-01-01")
e1 <- lubridate::as_datetime("2021-12-31 23:59:59")
n1 <- as.numeric(lubridate::as.duration(e1 - t))
s1 <- sample(seq.int(n1), 300L)
d1 <- tibble::tibble(dttm = t + s1) |>
dplyr::mutate(mon = lubridate::floor_date(dttm, "month")) |>
dplyr::summarise(total = dplyr::n(), .by = "mon")
d1 |>
ggplot2::ggplot(aes(x = mon, y = total)) +
ggplot2::geom_line() +
ggplot2::scale_x_datetime(
date_breaks = "3 months",
date_labels = "%b %y"
) +
labs(
title = "x axis labelled Mar-Jun-Sep-Dec as expected",
x = NULL,
y = NULL
)
e2 <- lubridate::as_datetime("2022-12-31 23:59:59")
n2 <- as.numeric(lubridate::as.duration(e2 - t))
s2 <- sample(seq.int(n2), 600L)
d2 <- tibble::tibble(dttm = t + s2) |>
dplyr::mutate(mon = lubridate::floor_date(dttm, "month")) |>
dplyr::summarise(total = dplyr::n(), .by = "mon")
d2 |>
ggplot2::ggplot(aes(x = mon, y = total)) +
ggplot2::geom_line() +
ggplot2::scale_x_datetime(
date_breaks = "3 months",
date_labels = "%b %y"
) +
labs(title = "x axis labelled with Feb-May-Aug-Nov", x = NULL, y = NULL)
d2 |>
ggplot2::ggplot(aes(x = mon, y = total)) +
ggplot2::geom_line() +
ggplot2::scale_x_datetime(
date_breaks = "1 months",
date_labels = "%b %y"
) +
labs(title = "x axis includes Dec 20 and Jan 23 (outside the dataset)", x = NULL, y = NULL) +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 0.5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment