How to manually change the x-axis label in ggplot?

Viewed 3349

I want to change the x-axis labels of my ggplot. Below is my sample code

DF <- data.frame(seq(as.Date("2001-04-01"), to= as.Date("2001-8-31"), by="day"),
                 A = runif(153, 0,10))
colnames(DF)<- c("Date", "A")
ggplot(DF, aes(x = Date, y = A))+
  geom_line()+
scale_x_date(date_labels = "%b", date_breaks = "month", name = "Month")

I tried scale_x_discrete(breaks = c(0,31,60,90,120), labels = c("Jan", "Feb","Mar","Apr","May")) with no success. I know my data is from April but would like to change the labels pretending that its from January.

1 Answers

You can use scale_x_date but pass a vector of date into breaks and a character vector in labels of the same length as described in the official documentation (https://ggplot2.tidyverse.org/reference/scale_date.html):

ggplot(DF,aes(x = Date, y = A, group = 1))+
  geom_line()+
  scale_x_date(breaks = seq(ymd("2001-04-01"),ymd("2001-08-01"), by = "month"),
                   labels = c("Jan","Feb","Mar","Apr","May"))

enter image description here

EDIT: Substract months using lubridate

Alternatively, using lubridate, you can substract 3 months and use this new date variable to plot your data:

library(lubridate)
library(dplyr)
library(ggplot2)

DF %>% mutate(Date2 = Date %m-% months(3))%>%
  ggplot(aes(x = Date2, y = A))+
  geom_line()+
  scale_x_date(date_labels = "%b", date_breaks = "month", name = "Month")

enter image description here

Does it look what you are trying to achieve ?

Related