Reputation: 343
When creating a bar plot where the x-axis is Weekdays (using lubridate and ggplot), the order of my weekdays does't follow the chronological "mon, tues, wed... "
I've tried to replicate the problem but as you can see below, in my replication, the order of labels on the x-axis if fine.
library(lubridate)
library(dplyr)
my_data <- data.frame(dates = sample(seq(as.Date('2010/01/01'), as.Date('2020/01/01'), by="day"), 100),
group = rep(c(1,2,3,4), times = 5))
my_data <- my_data %>%
mutate(Weekdays = wday(dates, label = TRUE)) %>%
filter(Weekdays != "Sat" &
Weekdays != "Sun")
ggplot(my_data, aes(Weekdays))+
geom_bar()+
facet_wrap(~group)
Output:
The code below is what I have used with the real data. As you can see the week days are not in order. I'm not sure where my actual code differs from the attempted replication above.
library(ggplot2)
df1 <- filter(df, wday != "Sat")
ggplot(df1, aes(x = wday))+
geom_bar()+
facet_wrap(~Grouping)+
theme(axis.text.x = element_text(angle =90, hjust = 1))
Output:
Any help / advice would be most appreciated.
Upvotes: 0
Views: 2039
Reputation: 21
I think this would be the solution
my_data %>%
mutate(weekday = fct_reorder(weekdays(dates, abbreviate = TRUE), # generating week days
wday(dates))) %>%
filter(!weekday %in% c("Sat", "Sun")) %>% # here you filter saturday and sunday
ggplot(aes(weekday)) +
geom_bar() +
facet_wrap(~ group)
As you can see, the wday function gives the ordered numbers that can be used with fct_reorder function.
Upvotes: 2