gaut
gaut

Reputation: 5958

Force time series x labels on each year

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

Upvotes: 0

Views: 39

Answers (2)

Quinten
Quinten

Reputation: 41573

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

Upvotes: 2

gaut
gaut

Reputation: 5958

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")

Upvotes: 0

Related Questions