Home > Blockchain >  Using ggplot scale_x_datetime() to set first date on x axis
Using ggplot scale_x_datetime() to set first date on x axis

Time:05-03

I've got a plot of water levels over two years. I have a column of date time (format POSIXct and displayed like 2020-03-05 17:00:00). There are 18,000 rows of data in the dataframe. The first record was the 5 March 2020. When I plot the data, the first date that appears on the x axis is Jul-20. How do I make this Mar-20?

This is the bit of code I have at the moment relevant to this part of the plot design.

scale_x_datetime(
      date_breaks="6 months",
      date_labels="%b-%y")

Heres an example of the plot.

enter image description here

NOTE: this is also part of ongoing data collection, so I don't want to hard code the last date.

CodePudding user response:

library(ggplot2)
dat <- data.frame(date = seq(as.Date("2020-03-05 17:00:00", 
                                     format = "%Y-%m-%d %H:%M:%S"), 
                             as.Date("2022-03-05 17:00:00", 
                                     format = "%Y-%m-%d %H:%M:%S"), 
                             length=18000))
dat$x <- rnorm(18000)
dat$date <- as.POSIXct(dat$date)                  


ggplot(dat, aes(x=date, y=x))   
  geom_line()   
  theme_classic()   
  scale_x_datetime(breaks= seq(min(dat$date), max(dat$date), length=6), 
                   date_labels="%b-%y")

Created on 2022-05-03 by the reprex package (v2.0.1)

CodePudding user response:

scale_x_date(breaks = seq(as.Date("2020-03-05"), as.Date(Sys.Date( )), by = "6 months"), date_labels="%b-%y")
  • Related