Home > OS >  How do I increase datetime ticks in ggplot (posixct)?
How do I increase datetime ticks in ggplot (posixct)?

Time:09-02

I am attempting to plot this dataset but increase the number of ticks on the x-axis.

        order_dates            Value
1     2022-08-28 00:00:10       80.9 
2     2022-08-28 00:16:40       81.6   
3     2022-08-28 00:33:28       81.2
4     2022-08-28 05:37:12       81.4
5     2022-08-28 08:52:24       89.0    
6     2022-08-28 09:50:28       100.6   
7     2022-08-28 12:30:08       84.9

ggplot() geom_line(data=z, aes(x=order_dates, y=Value), lwd = 0.5, alpha = 0.6)

This code results in x-ticks that are hourly, but I would like more ticks on the x-axis (say, every 30 minutes). order_dates is a Posixct class. Furthermore, I would like the x-axis to have both date and time (in the event I get different dates in the order_dates column). How can I achieve this? Thanks.

CodePudding user response:

You could use scale_x_datetime:

library(ggplot2)

ggplot()   
  geom_line(data=z, aes(x=order_dates, y=as.numeric(Value)), lwd = 0.5, alpha = 0.6)  
  scale_x_datetime(date_breaks = "30 min", date_labels = "%d/%m/%Y %H:%M")  
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

Output:

enter image description here

Data:

library(readr)

z <- read_delim("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-28 08:52:24,89.0
2022-08-28 09:50:28,100.6
2022-08-28 12:30:08,84.9")
  • Related