r - R:将日期从每天转换为每周并绘制它们
问题描述
我正在尝试学习如何处理时间序列数据。我创建了一些虚假的每日数据,尝试按周汇总,然后绘制它:
set.seed(123)
library(xts)
library(ggplot2)
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)
y.mon<-aggregate(property_damages_in_dollars~format(as.Date(date_decision_made),
format="%W"),data=final_data, FUN=sum)
y.mon$week = y.mon$`format(as.Date(date_decision_made), format = "%W")`
g = ggplot(y.mon, aes(x = week, y=property_damages_in_dollars) + geom_line(aes(group=1))
该图似乎有效,但轴上只有 52 个“刻度”,而应该是该数量的两倍(有 2 年的数据)。我认为将数据从每日转换为每周时出现问题 - 有人可以告诉我如何解决这个问题吗?
在我的实际数据中,我有 30 年的数据。日期似乎很拥挤。我试图“取消”日期:
library(scales)
g + scale_x_date(date_breaks = "1 week", expand = c(0,0)) +
theme(axis.text.x = element_text(angle=90, vjust=.5))
但这也行不通。有人可以告诉我我做错了什么吗?
谢谢
注意:如果有两列,是否仍然可以使用聚合函数?
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)
other_damages_in_dollars <- rnorm(731,10,10)
final_data <- data.frame(date_decision_made, other_damages_in_dollars, property_damages_in_dollars)
y.mon<-aggregate(property_damages_in_dollars, other_damages_in_dollars ~format(as.Date(date_decision_made),
format="%Y/%m"),data=final_data, FUN=sum)
解决方案
一种方法可以像这样将年份添加到一周中:
library(ggplot2)
#Code 1
#Data
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))
输出:
如果您感到好奇,我将在此处使用scale_x_date()
并直接针对日期进行聚合:
#Code 2
y.mon<-aggregate(property_damages_in_dollars~as.Date(date_decision_made),data=final_data, FUN=sum)
y.mon$week = y.mon$`as.Date(date_decision_made)`
#Plot
ggplot(y.mon, aes(x = week, y=property_damages_in_dollars)) +
geom_line(aes(group=1))+
scale_x_date(date_labels = '%Y-%W',breaks = '8 weeks')
输出:
推荐阅读
- java - 未解决的类“FileProvider”
- c# - .Net Native C# 应用程序无法通过 WACK 测试并避免 ILT005 错误
- c# - 将数量金额文本框值从子表单传递到父表单上的变量
- swift - 垂直和水平滚动collectionView选择单元格问题
- r - 为“TRUE”创建给定位置的逻辑向量
- python-3.x - CNN - 如何使用 keras 正确获取 val_loss 和 val_acc?
- mvvm - 如何使用 MVVM 为社区工具包 RadialGauge 制作动画?
- google-apps-script - 从 Google 表格发送提醒电子邮件和日历
- amazon-web-services - 更新 AWS Glue 表中的行/列
- bash - 如何使用 sed 或 grep 和正则表达式 json 提取文本