在ggplot2中订购x轴日期值 [英] Order x axis day values in ggplot2

查看:65
本文介绍了在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')

这篇关于在ggplot2中订购x轴日期值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆