Home > database >  How to show year in a date label only when it's a new year
How to show year in a date label only when it's a new year

Time:09-23

I'm plotting a time series graph across multiple years. I'd like each tick on the x-axis to indicate the year and month. But, I only want the year to appear sometimes

  • When it's the earliest date of that year on the graph, the date should be "%Y-%b"
  • When it's any other date that year, the format should be "%b"

Here's some example data

# Setup 
library(tidyverse)
library(patchwork)

# Set seed 
set.seed(123)

# Generate data
df_test <- 
  tibble(
    date = seq(as.Date("2010-1-1"), as.Date("2012-1-1"), by = "months"),
    value = rnorm(n = length(date), mean = 10, sd = 1))

And here's the graph atm

gg_full <- 
  df_test %>% 
  ggplot(
    aes(
      x = date, 
      y = value))  
  geom_line()   
  scale_x_date(
    date_breaks = "1 month",
    date_labels = "%b")   
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1))

gg_full

enter image description here

I'd like it to look something like this

enter image description here

If it's easier to plot the year labels separately beneath the month labels, that's also fine. I just want to indicate what year each month is in without having to include the year inside each and every month label.

CodePudding user response:

Use scales::label_date_short:

df_test %>% 
  ggplot(aes(x = date, y = value))  
  geom_line()   
  scale_x_date(date_breaks = "1 month",
               labels = scales::label_date_short())   
  theme(axis.text.x = element_text(angle = 0, hjust = 1))

enter image description here

  • Related