R中的每周数据图

时间:2016-06-29 14:00:35

标签: r plot

我有一个大数据框架(从2007年到2015年),数据点大约每2分钟一次。我想绘制每周(从2007年到2015年)的图表,每周自动导出为PNG文件到我的计算机文件夹。以前,我能够成功地生成每年,每月和每日情节的工作代码。例如,年度数据:

for(j in 2007:2015){
mypath <- file.path("~", "Documents","Yearly", paste("WAO_AIR_Data_", j, ".png", sep = "" ))
png(filename = mypath, width = 963, height = 690) 
timePlot(selectByDate(new_subdata, year = j), 
       pollutant = c("CO2", "O2", "APO"), 
       date.pad = TRUE,
       pch = c(19,19,19),
       cex = 0.2,
       xlab = paste("Month of year in", j),
       ylab = "CO2, O2, and APO concentrations",
       name.pol = c("CO2 (ppm)", "O2 (per meg)", "APO (per meg)"),
)
dev.off()
}

数据框看起来像这样

tail(new_subdata)
                   date     CO2      O2     APO
1052042 2015-12-31 23:48:45 409.636 -666.39 -353.27
1052043 2015-12-31 23:50:46 409.652 -669.62 -356.41
1052044 2015-12-31 23:52:44 409.679 -669.44 -356.09
1052045 2015-12-31 23:54:46 409.703 -667.07 -353.59
1052046 2015-12-31 23:56:44 409.719 -671.02 -357.46
1052047 2015-12-31 23:58:46 409.734      NA      NA

但我不知道如何制作每周绘图的代码。有人可以帮我吗?非常感谢你!

1 个答案:

答案 0 :(得分:1)

通过?strptime,您可以DatePOSIXct%U

一起度过一周
  

%U   一年中的一周作为十进制数(00-53),使用星期日作为一周的第一天1(并且通常以一年的第一个星期日作为第1周的第1天)。美国公约。

x <- Sys.time()
class(x); format(x, '%U')
# [1] "POSIXct" "POSIXt" 
# [1] "26"

x <- Sys.Date()
class(x); format(x, '%U')
# [1] "Date"
# [1] "26"

使用您的示例数据进行细微更改:

new_subdata <- read.table(header = TRUE, text = "date     CO2      O2     APO
1052042 '2015-10-31 23:48:45' 409.636 -666.39 -353.27
1052043 '2015-10-31 23:50:46' 409.652 -669.62 -356.41
1052044 '2015-11-30 23:52:44' 409.679 -669.44 -356.09
1052045 '2015-11-30 23:54:46' 409.703 -667.07 -353.59
1052046 '2015-12-31 23:56:44' 409.719 -671.02 -357.46
1052047 '2015-12-31 23:58:46' 409.734      NA      NA")

## create a new grouping variable with year/week
new_subdata <- within(new_subdata, {
  yr_wk <- format(as.Date(date), '%Y %U')
})

## iterate over the unique values
jj <- unique(new_subdata$yr_wk)
# [1] "2015 43" "2015 48" "2015 52"

## do some plotting
par(mfrow = n2mfrow(length(jj)), las = 1, mar = c(5,6,2,2),
    tcl = .2, mgp = c(3,.25,0))
xr <- range(new_subdata$O2, na.rm = TRUE)
yr <- range(new_subdata$CO2, na.rm = TRUE)

for (j in jj) {
  mypath <- file.path("~", "Documents","Yearly", sprintf("WAO_AIR_Data_%s.png", j))
  # png(filename = mypath, width = 963, height = 690)
  plot(CO2 ~ O2, data = subset(new_subdata, yr_wk == j), xlim = xr, ylim = yr)
  # dev.off()
}

myplot

相关问题