Skip to content

how to make a two lines x-axis (year and date) using ggh4x? #133

Answered by teunbrand
yippiekahee asked this question in Q&A
Discussion options

You must be logged in to vote

You can use the date_breaks argument in scale_x_date() to separate year from day/month with a special delimiter, and then let guide_axis_nested() know about this delimiter.

library(dplyr)
library(ggplot2)
library(ggh4x)

start_date <- as.Date("2022-01-01")
end_date <- as.Date("2023-12-31")
random_dates <- sample(seq(start_date, end_date, by="days"), 10, replace=TRUE)
random_values <- runif(10, min = 0, max = 20)
df <- data.frame(date = random_dates, value = random_values)

df %<>%
  mutate(date = as.Date(date)) %>%
  mutate(year = format(date, "%Y"))

ggplot(df) +
  geom_point(aes(x = date, y = value, group = 1)) +
  scale_x_date(
    date_labels = "%d-%m+%Y",
    guide = guide_axis_nested(

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@yippiekahee
Comment options

Answer selected by yippiekahee
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants