D. Studer
D. Studer

Reputation: 1875

ggplot: Sort by weekday

Can someone please tell me how I can change the order of the weekdays so that monday comes first and sunday last? (sorry my language settings are in German)

library(lubridate)
library(dplyr)

df <- data.frame(dat = as.POSIXlt(c("2021-01-04 00:00:01", 
"2021-01-2 00:00:01",
"2021-01-03 00:00:01", 
"2021-01-03 00:00:01", 
"2021-01-01 00:00:01", 
"2021-01-06 00:00:01", 
"2021-01-07 00:00:01", 
"2021-01-08 00:00:01"))) %>%
  mutate(weekday = weekdays(dat))

ggplot(df, aes(x = weekday)) + geom_bar()

enter image description here

Upvotes: 0

Views: 162

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389155

You can set the factor levels in the order that you want.

library(dplyr)
library(ggplot2)

df <- data.frame(dat = as.POSIXlt(c("2021-01-04 00:00:01", 
                                    "2021-01-2 00:00:01",
                                    "2021-01-03 00:00:01", 
                                    "2021-01-03 00:00:01", 
                                    "2021-01-01 00:00:01", 
                                    "2021-01-06 00:00:01", 
                                    "2021-01-07 00:00:01", 
                                    "2021-01-08 00:00:01"))) %>%
  mutate(weekday = weekdays(dat), 
         weekday = factor(weekday, c('Montag', 'Dienstag', 'Mittwoch', 
                    'Donnerstag', 'Freitag', 'Samstag', 'Sonntag')))

ggplot(df, aes(x = weekday)) + geom_bar()

Upvotes: 2

Related Questions