plot_na_ts.R 2.15 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

#' plot_na_ts

#' plot_na_ts
#' @param x object of class tbl_friendlyts
#' @param fromDate fromDate
#' @param toDate toDate
#' @param timeResolution timeResolution
#' @param tzone tzone
#' @param path path
#' @param name name
#' @param width_mm width_mm
#' @param height_mm height_mm
#' @param DESKTOP boolean
#' @keywords friendlyts
#' @export
#' @examples
#' \dontrun{
#' plot_na_ts()
#' }
plot_na_ts <- function(x,fromDate=NULL,toDate=NULL,timeResolution=NULL,tzone="UTC",path=tempdir(),name=NULL,width_mm=200,height_mm=200,DESKTOP=TRUE){


  # sub-period
  if (!is.null(fromDate) && !is.null(toDate) && !is.null(timeResolution)) {
     tmp <- friendlyts::sub_period(tbl_fts=x,fromDate=fromDate,toDate=toDate,timeResolution=timeResolution,tzone=tzone)
  } else tmp <- x

  df <- friendlyts::dfts(tbl_fts=tmp,timeResolution=timeResolution,tzone=tzone)
  df[["date"]] <- as.POSIXct(df[["date"]])

#  cat("df \n")
#  print(df)

  target <- setdiff(names(df), "date")

  tmp <- lapply(target,function(y) {
    res <- rep(1,length(df[[y]]))
    res[is.na(df[[y]])] <- NA
    res <- data.frame(date=df[["date"]],notna=res,target=y,stringsAsFactors=FALSE)
    return(res)
  })

  tmp <- do.call("rbind",tmp)
  tmp <- data.frame(date=tmp[,"date"],notna=tmp[,"notna"]*as.integer(as.factor(tmp[,"target"])),target = as.factor(tmp[,"target"]))

#  cat("tmp \n")
#  print(head(tmp))

    #start plot
  if (!(DESKTOP)) {

    if(is.null(name)) {
      filename <- normalizePath(file.path(path,paste0("na_ts.tiff")),mustWork = FALSE)
    } else filename <-normalizePath(file.path(path,paste0("na_ts_",name,".tiff")),mustWork = FALSE)

    grDevices::tiff(filename = filename, width = width_mm, height = height_mm,
          units = "mm", pointsize = 12,
          compression = "lzw",
          bg = "transparent", res = 300)

  } else grDevices::dev.new()

  # plot


  p <- ggplot2::ggplot(tmp, ggplot2::aes(x=date,y=notna,colour=target)) +
  ggplot2::geom_point() +
  ggplot2::labs(x = "date",y = "") #+
  #ggplot2::theme(axis.line.y=ggplot2::element_blank(),axis.text.y=ggplot2::element_blank())

  print(p)

  if (!(DESKTOP)) {
    grDevices::dev.off()
    return(filename)
  } else {
    return(TRUE)
  }

}