Home > Net >  ggplot2: force time series x labels on each year
ggplot2: force time series x labels on each year

Time:06-30

Below I create a reproducible example chart ranging for 10000 days. As you can see this chart is highly informative and value adding, but it will do for the example.

Instead of one x label every 10 years, I would like to force a label every year. How can this be achieved?

library(ggplot2)
library(tidyr)
exdays <- 1:10000
exdata <- sin(exdays)
exdate <- as_date("2022-01-01") days(exdays)
exdat <- tibble(exdate, exdata)
p1 <- ggplot(exdat, aes(x=exdate, y=exdata))  
  geom_line(color="darkred", size=0.7)  
  ggtitle("example")
p1

enter image description here

CodePudding user response:

You maybe want this using scale_x_date with date_breaks of 1 year where you specify the date_labels:

library(ggplot2)
library(tidyr)
exdays <- 1:10000
exdata <- sin(exdays)
exdate <- as_date("2022-01-01") days(exdays)
exdat <- tibble(exdate, exdata)
p1 <- ggplot(exdat, aes(x=exdate, y=exdata))  
  geom_line(color="darkred", size=0.7)  
  scale_x_date(date_breaks = "1 year", date_labels = "%Y")  
  ggtitle("example")
p1

Output:

enter image description here

CodePudding user response:

This works

p1 <- ggplot(exdat, aes(x=exdate, y=exdata))  
  geom_line(color="darkred", size=0.7)  
  ggtitle("example")   scale_x_date(date_breaks = "1 year")
  • Related