Andres Alvarado Andres Alvarado - 23 days ago 8
R Question

Order x axis day values in ggplot2

I have below dataset. As you can see I have some quantitative for two weeks and Id like to make a comparison between their days ( i.e: Monday 09 with Monday 10 ):

week date day n
(chr) (date) (chr) (int)
1 Week 09 2016-02-29 Monday 5535
2 Week 09 2016-03-01 Tuesday 7497
3 Week 09 2016-03-02 Wednesday 8658
4 Week 09 2016-03-03 Thursday 6113
5 Week 09 2016-03-04 Friday 4553
6 Week 09 2016-03-05 Saturday 2
7 Week 10 2016-03-07 Monday 5339
8 Week 10 2016-03-08 Tuesday 6196
9 Week 10 2016-03-09 Wednesday 5395
10 Week 10 2016-03-10 Thursday 5633


I got below code, but days are unordered.Is there anyway I can order these days in chronological order:

ggplot(data = my_data, aes(x = as.factor(x = day),
y = n,
col = week,
group = week)) +
geom_line() +
geom_point()


enter image description here

Answer Source

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