Order x axis day values in ggplot2

You need to reorder the levels of the day, which is what determines plotting order. You can either type out the days of the week, or use your favorite method for generating a sequence of Sunday to Saturday dates and call weekdays (or format or strftime with format = %A) on it. You can either do this on your data.frame before you plot (a good idea, as that’s the best way to store the data anyway), or inside of aes when you plot:

ggplot(data = my_data, aes(x = factor(day, weekdays(min(my_data$date) + 0:6)), 
                           y = n, 
                           col = week, 
                           group = week)) + 
    geom_line() + geom_point() + xlab('Weekday')

plot with nicely ordered weekdays

Leave a Comment