如何按时间顺序排列x轴(在图形中)? [英] how to order the x-axis (in a graph) in chronological order?

查看:64
本文介绍了如何按时间顺序排列x轴(在图形中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每天都会在R中创建一些伪造的(时间序列)数据.我想汇总"按周"划分数据,然后绘制数据.我已经在下面发布了我的代码:

I create some fake (time series) data in R at daily intervals. I want to "aggregate" the data by "week", and then plot the data. I have posted my code below:

#set seed
set.seed(123)

#load libraries
library(xts)
library(ggplot2)

#create data

date_decision_made = seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")

date_decision_made <- format(as.Date(date_decision_made), "%Y/%m/%d")

property_damages_in_dollars <- rnorm(731,100,10)

final_data <- data.frame(date_decision_made, property_damages_in_dollars)



#aggregate
y.mon<-aggregate(property_damages_in_dollars~format(as.Date(date_decision_made),
                                                    format="%W-%y"),data=final_data, FUN=sum)

y.mon$week = y.mon$`format(as.Date(date_decision_made), format = "%W-%y")`

#Plot
ggplot(y.mon, aes(x = week, y=property_damages_in_dollars))+
         geom_line(aes(group=1))+
  scale_x_discrete(guide = guide_axis(n.dodge=2))+
  theme(axis.text.x = element_text(angle = 45))

但是,图形的x轴似乎不是按时间顺序排列的.这些要点似乎是交替"的.在2014年至2015年之间.

However, the x-axis for the graph does not appear to be in chronological order. The points seem to be "alternating" between 2014 and 2015.

有人可以告诉我如何解决此问题吗?

Can someone please show me how to fix this?

推荐答案

正如@Allan所说,如果将日期保留为日期并使用 scale_x_date 设置X轴格式并指定其间断,这很容易.您想要的方式.

As @Allan mentioned it is easy if you keep dates as dates and use scale_x_date to format X-axis and specify their breaks the way you want.

library(dplyr)
library(ggplot2)

final_data %>%
  mutate(date_decision_made = as.Date(date_decision_made, "%Y/%m/%d"),
         week = format(date_decision_made, "%W-%y")) %>%
  group_by(week) %>%
  summarise(property_damages_in_dollars = sum(property_damages_in_dollars), 
            date = first(date_decision_made)) %>%
  ggplot() + aes(x = date, y=property_damages_in_dollars) + 
  geom_line(aes(group=1)) +
  scale_x_date(date_labels = "%W-%y", date_breaks = '1 month') + 
  theme(axis.text.x = element_text(angle = 45))

这篇关于如何按时间顺序排列x轴(在图形中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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