Home > Net >  How do I display the date only once but have a tick every few hours in ggplot?
How do I display the date only once but have a tick every few hours in ggplot?

Time:09-03

Here is the dataset in question

z <- read.csv(text="order_dates,Value
2022-08-28 00:00:10,80.9 
2022-08-28 00:16:40,81.6   
2022-08-28 00:33:28,81.2
2022-08-28 05:37:12,81.4
2022-08-29 08:52:24,89.0    
2022-08-29 09:50:28,100.6   
2022-08-29 12:30:08,84.9")
z$order_dates <- as.POSIXct(z$order_dates)
ggplot()   
  geom_line(data=z, aes(x=order_dates, y=Value), lwd = 0.5, alpha = 0.6)   
  scale_x_datetime(date_breaks = "2 hours", date_labels = "%m/%d %H:%M")

This code results in the date being displayed on every tick. As previously stated, I would like for it to be shown only once per day -- and a tick for every 2 hours.

CodePudding user response:

If you use labels = instead of date_labels =, you can specify a labelling function that takes date times and formats them however you please. You could use this to convert any date-times that aren't at midnight to time strings, and use your desired date-time format otherwise:

ggplot()   
  geom_line(data=z, aes(x=order_dates, y=Value), lwd = 0.5, alpha = 0.6)   
  scale_x_datetime(date_breaks = "2 hours", 
                   labels = ~ ifelse(substr(.x, 12, 19) == '00:00:00', 
                                     strftime(.x, "%H:%M\n%m/%d"),
                                     strftime(.x, '%H:%M'))) 

enter image description here

CodePudding user response:

You can do this by using date_breaks function from library scales.

library(ggplot2)
library(scales)
z <- read.csv(text="order_dates,Value
2022-08-28 00:00:10,80.9 
2022-08-28 00:16:40,81.6
2022-08-28 00:33:28,81.2
2022-08-28 05:37:12,81.4
2022-08-29 08:52:24,89.0
2022-08-29 09:50:28,100.6
2022-08-29 12:30:08,84.9")
z$order_dates <- as.POSIXct(z$order_dates)

ggplot()  
geom_line(data=z, aes(x=order_dates, y=Value), lwd = 0.5, alpha = 0.6)  
scale_x_datetime(date_labels = "%m/%d %H:%M",breaks = date_breaks("2 hours")) 
theme(axis.text.x = element_text(angle = 90, vjust = 1.0, hjust = 1.0))

enter image description here

  • Related