简体   繁体   中英

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:

             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. 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)? I tried 'ggplot2' package which removes all missing values. Trying 'zoo' package doesn't allow x-axis to be plotted as month-year. Any suggestion?

This should not be problematic for any of R's plotting packages. I'm not a ggplot user, but here's a base R example using a slightly modified version of your data. Note that using as.POSIXct is preferable to using as.POSIXlt within data.frame objects:

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:

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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