Cameron
Cameron

Reputation: 367

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

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

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.

Upvotes: 1

Views: 779

Answers (1)

Ma&#235;l
Ma&#235;l

Reputation: 52399

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

Upvotes: 3

Related Questions