plot_boxwhisk_ts.R 1.87 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

#' plot_boxwhisk_ts

#' plot_boxwhisk_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 y_name name on the y-axis
#' @param DESKTOP boolean
#' @keywords friendlyts
#' @export
#' @examples
#' \dontrun{
#' plot_boxwhisk_ts()
#' }
plot_boxwhisk_ts <- function(x,fromDate=NULL,toDate=NULL,timeResolution=NULL,tzone="UTC",path=tempdir(),name=NULL,width_mm=200,height_mm=200,y_name="Y-axis",DESKTOP=TRUE){


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

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

  #start plot
  if (!(DESKTOP)) {

    if(is.null(name)) {
      filename <- normalizePath(file.path(path,paste0("boxwhisk_ts.tiff")),mustWork = FALSE)
    } else filename <-normalizePath(file.path(path,paste0("boxwhisk_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(df, ggplot2::aes(x=date)) +
       ggplot2::geom_boxplot(
                             ggplot2::aes(ymin = q_0, lower = q_0_25, middle = q_0_5, upper = q_0_75, ymax = q_1),
                             stat = "identity") +
       ggplot2::geom_line(ggplot2::aes(y=value)) +
       ggplot2::labs(x = "date",y = y_name)

  print(p)

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

}