Reputation: 343
I want to change the order in which the x-axis labels are displayed. Below is my sample data and my graph. You can see, that the 23:30 mark is on the far right. The x-axis should start by 23:30 on the left, so that all the bars are nicely condensed.
DF <- data.frame(time = as.POSIXct(c("1970-01-01 23:30:00", "1970-01-01 23:30:00", "1970-01-01 23:30:00", "1970-01-01 00:00:00", "1970-01-01 00:00:00",
"1970-01-01 00:30:00", "1970-01-01 00:30:00", "1970-01-01 01:00:00", "1970-01-01 01:30:00", "1970-01-01 01:30:00")))
library(ggplot2)
ggplot(data = DF) +
geom_bar(aes(x = time))+
scale_x_datetime(date_breaks = "30 min", date_labels = "%H:%M")+
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
I tried to add something like limits = (c(as.POSIXct(min("1970-01-01 23:30"), max("1970-01-01 10:00")))) but it just give me error messages:
Removed 7 rows containing non-finite values (stat_count)
1: In strptime(xx, f, tz = tz) : unknown timezone '1970-01-01 10:00'
2: In as.POSIXct.POSIXlt(x) : unknown timezone '1970-01-01 10:00'
I'd be really glad about some help!
Upvotes: 1
Views: 353
Reputation: 8117
Does this help?
DF %>%
mutate(time = if_else(hour(time) > 4, time - days(1), time)) %>%
ggplot(aes(time)) +
geom_bar() +
scale_x_datetime(date_breaks = "30 min", date_labels = "%H:%M")+
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
The point is that 23:30 is after 01:00 and therefore should be on the right. If you want these times to be on the left, you need to change the date (virtually) if the time is after some cut-off point. The date_labels
argument only changes what is displayed on the axis.
Upvotes: 3