在ggplot2中订购x轴日期值

问题描述:

我有下面的数据集。正如你所看到的,我有两个星期的定量数据,并且我想在他们的日子之间进行比较(即:周一09和周一10):

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()

您需要重新排列,这决定了绘图顺序。您可以输入一周中的某几天,也可以使用自己喜欢的方法生成一系列周日至周六日期,并调用周日(或格式 strftime format =%A )。你可以在绘制数据之前对其进行绘图(这是一个好主意,因为这是存储数据的最佳方式),或者在绘图时绘制 aes :数据= my_data,aes(x = factor(day,weekdays(min(my_data $ date)+ 0):

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')