Home > Software engineering >  Specify shown labels for date x axis ggplot2
Specify shown labels for date x axis ggplot2

Time:05-17

I have the following example dataframe and code:

library(ggplot2)

data <- data.frame(date=as.Date(c("05.08.2021","07.08.2021","09.08.2021","27.08.2021","02.09.2021"), format = "%d.%m.%Y"),event=as.numeric(c("1", "2", "3", "4", "5")))
    
ggplot(data=data, aes(x=date, y=event, group=1)) 
  geom_line() 
  geom_point()

The outputted plot shows random dates on the x axis. I want R to show only five given dates on the x axis.

Thanks for your help!

CodePudding user response:

Use scale_x_date:

ggplot(data=data, aes(x = date, y=event, group=1)) 
  geom_line()  
  geom_point()  
  scale_x_date(breaks = data$date, labels = format(data$date, "%b %d"))

enter image description here

  • Related