简体   繁体   English

使用R在单个图中缺少值的多个时间序列数据

[英]Multiple time-series data with missing values in a single plot using R

I have prepared a data frame ordered according to date and time as.POSIXlt: 我准备了一个按照日期和时间排序的数据框,如POSIXlt:

             Date_Time A1    B2 C1    E2
46 24/06/2012 12:20:00 NA 5.515 20    NA
47 24/06/2012 13:20:00 41    NA NA 3.519
48 25/06/2012 14:00:00 NA    NA NA    NA
49 25/06/2012 14:20:00 30    NA 30    NA
50 27/06/2012 15:20:00 NA    71 NA    NA
51 28/06/2012 18:00:00 11    NA 55    11
... ...

As you can see it contains a lot of 'NA' values. 如您所见,它包含很多“ NA”值。 Is it possible to plot all data in a single plot with the 'x-axis' showing month-year and different colors assigned for different data (eg green for A1, blue for C1)? 是否可以在单个绘图中绘制所有数据,并在“ x轴”上显示月份年份,并为不同的数据分配不同的颜色(例如,A1为绿色,C1为蓝色)? I tried 'ggplot2' package which removes all missing values. 我尝试了“ ggplot2”软件包,该软件包删除了所有缺失的值。 Trying 'zoo' package doesn't allow x-axis to be plotted as month-year. 尝试使用“ zoo”程序包不允许将x轴绘制为月-年。 Any suggestion? 有什么建议吗?

This should not be problematic for any of R's plotting packages. 对于任何R的绘图软件包来说,这都不成问题。 I'm not a ggplot user, but here's a base R example using a slightly modified version of your data. 我不是ggplot用户,但这是一个使用数据稍有修改版本的基本R示例。 Note that using as.POSIXct is preferable to using as.POSIXlt within data.frame objects: 请注意,使用as.POSIXct优选使用as.POSIXltdata.frame对象:

dat <- read.csv(text="Date_Time,A1,B2,C1,E2
24/06/2012 12:20:00,NA,5.515,20,NA
24/06/2012 13:20:00,41,NA,NA,3.519
25/06/2012 14:00:00,NA,NA,NA,NA
25/07/2012 14:20:00,30,NA,30,NA
27/08/2012 15:20:00,NA,71,NA,NA
28/09/2012 18:00:00,11,NA,55,11")

dat$Date_Time <- as.POSIXct(dat$Date_Time,format="%d/%m/%Y %H:%M:%S")

matplot(
  dat[,1],
  dat[2:5],
  type="o",
  pch=19,
  col=c("green","red","blue","black"),
  xaxt="n",
  xlab="Year-Month",
  ylab="Value"
)

Add a POSIXct represented axis with a chosen format: 添加具有选定格式的POSIXct表示的轴:

axis.POSIXct(side=1,x=dat$Date_Time,format="%Y-%m")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM