Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ggplot scale_x_datetime() to set first date on x axis [duplicate]

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.

like image 838
Melanie Baker Avatar asked Dec 19 '25 02:12

Melanie Baker


1 Answers

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)

like image 74
DaveArmstrong Avatar answered Dec 20 '25 16:12

DaveArmstrong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!