blob: fc07ce560cdd32be82d9897628e33845fd7d5a5b [file] [log] [blame]
Hao Zhu5fe235c2020-08-26 00:26:49 -04001#' Helper functions to generate inline sparklines
2#'
3#' @description These functions helps you quickly generate sets of sparkline
Bill Evans5a383e52020-08-30 20:09:52 -07004#' style plots using base R plotting system. Currently, we support histogram,
Bill Evanscebc9712020-08-30 19:55:24 -07005#' boxplot, and line. You can use them together with `column_spec` to
Hao Zhu5fe235c2020-08-26 00:26:49 -04006#' generate inline plot in tables. By default, this function will save images
7#' in a folder called "kableExtra" and return the address of the file.
8#'
9#' @param x Vector of values or List of vectors of values.
10#' @param width The width of the plot in pixel
11#' @param height The height of the plot in pixel
12#' @param res The resolution of the plot. Default is 300.
13#' @param same_lim T/F. If x is a list of vectors, should all the plots be
14#' plotted in the same range? Default is True.
Hao Zhudefd1892020-09-09 00:08:09 -040015#' @param lim Manually specify plotting range in the form of
16#' `c(0, 10)`.
Hao Zhu5fe235c2020-08-26 00:26:49 -040017#' @param xaxt On/Off for xaxis text
18#' @param yaxt On/Off for yaxis text
19#' @param ann On/Off for annotations (titles and axis titles)
20#' @param col Color for the fill of the histogram bar/boxplot box.
21#' @param border Color for the border.
22#' @param dir Directory of where the images will be saved.
23#' @param file File name. If not provided, a random name will be used
Bill Evans95a04282020-09-14 12:39:25 -070024#' @param file_type Graphic device. Can be character (e.g., `"pdf"`)
25#' or a graphics device function (`grDevices::pdf`). This defaults
26#' to `"pdf"` if the rendering is in LaTeX and `"svg"` otherwise.
Hao Zhu5fe235c2020-08-26 00:26:49 -040027#' for HTML output
Hao Zhudefd1892020-09-09 00:08:09 -040028#' @param ... extra parameters sending to `hist()`
Hao Zhu5fe235c2020-08-26 00:26:49 -040029#'
Hao Zhu5fe235c2020-08-26 00:26:49 -040030#' @export
31spec_hist <- function(x, width = 200, height = 50, res = 300,
32 breaks = "Sturges",
33 same_lim = TRUE, lim = NULL,
34 xaxt = 'n', yaxt = 'n', ann = FALSE,
35 col = "lightgray", border = NULL,
36 dir = if (is_latex()) rmd_files_dir() else tempdir(),
37 file = NULL,
Bill Evans95a04282020-09-14 12:39:25 -070038 file_type = if (is_latex()) "pdf" else "svg", ...) {
Hao Zhu5fe235c2020-08-26 00:26:49 -040039 if (is.list(x)) {
40 if (same_lim & is.null(lim)) {
41 lim <- base::range(unlist(x))
42 }
Bill Evans95a04282020-09-14 12:39:25 -070043
44 dots <- listify_args(x, width, height, res, breaks,
45 lim, xaxt, yaxt, ann, col, border,
46 dir, file, file_type,
47 lengths = c(1, length(x)))
48 return(do.call(Map, c(list(f = spec_hist), dots)))
Hao Zhu5fe235c2020-08-26 00:26:49 -040049 }
50
Bill Evans8def4da2020-09-11 09:58:26 -070051 if (is.null(x)) return(NULL)
52
Hao Zhu5fe235c2020-08-26 00:26:49 -040053 if (is.null(lim)) {
54 lim <- base::range(x)
55 }
56
Hao Zhu5fe235c2020-08-26 00:26:49 -040057 if (!dir.exists(dir)) {
58 dir.create(dir)
59 }
60
Bill Evans95a04282020-09-14 12:39:25 -070061 file_ext <- dev_chr(file_type)
Hao Zhu5fe235c2020-08-26 00:26:49 -040062 if (is.null(file)) {
Bill Evans95a04282020-09-14 12:39:25 -070063 file <- normalizePath(
64 tempfile(pattern = "hist_", tmpdir = dir, fileext = paste0(".", file_ext)),
65 winslash = "/", mustWork = FALSE)
Hao Zhu5fe235c2020-08-26 00:26:49 -040066 }
67
Bill Evans95a04282020-09-14 12:39:25 -070068 graphics_dev(filename = file, dev = file_type,
69 width = width, height = height, res = res,
70 bg = "transparent")
71 curdev <- grDevices::dev.cur()
72 on.exit(grDevices::dev.off(curdev), add = TRUE)
Hao Zhu5fe235c2020-08-26 00:26:49 -040073
74 graphics::par(mar = c(0, 0, 0.2, 0), lwd=0.5)
75 graphics::hist(x, breaks = breaks, xlim = lim, border = border,
76 xaxt = xaxt, yaxt = yaxt, ann = ann, col = col, ...)
Hao Zhu5fe235c2020-08-26 00:26:49 -040077
Bill Evans95a04282020-09-14 12:39:25 -070078 grDevices::dev.off(curdev)
Hao Zhu5fe235c2020-08-26 00:26:49 -040079
Bill Evans95a04282020-09-14 12:39:25 -070080 out <- make_inline_plot(
81 file, file_ext, file_type,
82 width, height, res,
83 del = TRUE)
Hao Zhu5fe235c2020-08-26 00:26:49 -040084 return(out)
85}
86
Hao Zhudefd1892020-09-09 00:08:09 -040087#' Helper functions to generate inline sparklines
88#'
89#' @description These functions helps you quickly generate sets of sparkline
90#' style plots using base R plotting system. Currently, we support histogram,
91#' boxplot, and line. You can use them together with `column_spec` to
92#' generate inline plot in tables. By default, this function will save images
93#' in a folder called "kableExtra" and return the address of the file.
94#'
95#' @param x Vector of values or List of vectors of values.
96#' @param width The width of the plot in pixel
97#' @param height The height of the plot in pixel
98#' @param res The resolution of the plot. Default is 300.
99#' @param add_label For boxplot. T/F to add labels for min, mean and max.
100#' @param label_digits If T for add_label, rounding digits for the label.
101#' Default is 2.
102#' @param same_lim T/F. If x is a list of vectors, should all the plots be
103#' plotted in the same range? Default is True.
104#' @param lim,xlim,ylim Manually specify plotting range in the form of
105#' `c(0, 10)`. `lim` is used in `spec_hist` and `spec_boxplot`; `xlim`
Bill Evans548d7152020-09-13 21:44:24 -0700106#' and `ylim` are used in `spec_plot`.
Hao Zhudefd1892020-09-09 00:08:09 -0400107#' @param xaxt On/Off for xaxis text
108#' @param yaxt On/Off for yaxis text
109#' @param ann On/Off for annotations (titles and axis titles)
110#' @param col Color for the fill of the histogram bar/boxplot box.
111#' @param border Color for the border.
112#' @param boxlty Boxplot - box boarder type
113#' @param medcol Boxplot - median line color
114#' @param medlwd Boxplot - median line width
115#' @param dir Directory of where the images will be saved.
116#' @param file File name. If not provided, a random name will be used
Bill Evans95a04282020-09-14 12:39:25 -0700117#' @param file_type Graphic device. Can be character (e.g., `"pdf"`)
118#' or a graphics device function (`grDevices::pdf`). This defaults
119#' to `"pdf"` if the rendering is in LaTeX and `"svg"` otherwise.
Hao Zhudefd1892020-09-09 00:08:09 -0400120#' @param ... extraparameters passing to boxplot
121#'
Hao Zhu5fe235c2020-08-26 00:26:49 -0400122#' @export
123spec_boxplot <- function(x, width = 200, height = 50, res = 300,
124 add_label = FALSE, label_digits = 2,
125 same_lim = TRUE, lim = NULL,
126 xaxt = 'n', yaxt = 'n', ann = FALSE,
127 col = "lightgray", border = NULL,
128 boxlty = 0, medcol = "red", medlwd = 1,
129 dir = if (is_latex()) rmd_files_dir() else tempdir(),
130 file = NULL,
Bill Evans95a04282020-09-14 12:39:25 -0700131 file_type = if (is_latex()) "pdf" else "svg", ...) {
Hao Zhu5fe235c2020-08-26 00:26:49 -0400132 if (is.list(x)) {
133 if (same_lim & is.null(lim)) {
134 lim <- base::range(unlist(x))
135 }
Bill Evans95a04282020-09-14 12:39:25 -0700136
137 dots <- listify_args(x, width, height, res,
138 add_label, label_digits,
139 lim, xaxt, yaxt, ann, col, border,
140 dir, file, file_type,
141 lengths = c(1, length(x)))
142 return(do.call(Map, c(list(f = spec_boxplot), dots)))
Hao Zhu5fe235c2020-08-26 00:26:49 -0400143 }
144
Bill Evans8def4da2020-09-11 09:58:26 -0700145 if (is.null(x)) return(NULL)
146
Hao Zhu5fe235c2020-08-26 00:26:49 -0400147 if (is.null(lim)) {
148 lim <- base::range(x)
149 lim[1] <- lim[1] - (lim[2] - lim[1]) / 10
150 lim[2] <- (lim[2] - lim[1]) / 10 + lim[2]
151 }
152
Hao Zhu5fe235c2020-08-26 00:26:49 -0400153 if (!dir.exists(dir)) {
154 dir.create(dir)
155 }
156
Bill Evans95a04282020-09-14 12:39:25 -0700157 file_ext <- dev_chr(file_type)
Hao Zhu5fe235c2020-08-26 00:26:49 -0400158 if (is.null(file)) {
Bill Evans95a04282020-09-14 12:39:25 -0700159 file <- normalizePath(
160 tempfile(pattern = "boxplot_", tmpdir = dir, fileext = paste0(".", file_ext)),
161 winslash = "/", mustWork = FALSE)
Hao Zhu5fe235c2020-08-26 00:26:49 -0400162 }
163
Bill Evans95a04282020-09-14 12:39:25 -0700164 graphics_dev(filename = file, dev = file_type,
165 width = width, height = height, res = res,
166 bg = "transparent")
167 curdev <- grDevices::dev.cur()
168 on.exit(grDevices::dev.off(curdev), add = TRUE)
Hao Zhu5fe235c2020-08-26 00:26:49 -0400169
170 graphics::par(mar = c(0, 0, 0, 0))
171
172 graphics::boxplot(x, horizontal = TRUE, ann = ann, frame = FALSE, bty = 'n', ylim = lim,
173 col = col, border = border,
174 boxlty = boxlty, medcol = medcol, medlwd = medlwd,
175 axes = FALSE, outcex = 0.2, whisklty = 1,
176 ...)
177 if (add_label) {
178 x_median <- round(median(x, na.rm = T), label_digits)
179 x_min <- round(min(x, na.rm = T), label_digits)
180 x_max <- round(max(x, na.rm = T), label_digits)
181 graphics::text(x_median, y = 1.4, labels = x_median, cex = 0.5)
182 graphics::text(x_min, y = 0.6, labels = x_min, cex = 0.5)
183 graphics::text(x_max, y = 0.6, labels = x_max, cex = 0.5)
184 }
Hao Zhu5fe235c2020-08-26 00:26:49 -0400185
Bill Evans95a04282020-09-14 12:39:25 -0700186 grDevices::dev.off(curdev)
187
188 out <- make_inline_plot(
189 file, file_ext, file_type,
190 width, height, res,
191 del = TRUE)
Hao Zhu5fe235c2020-08-26 00:26:49 -0400192 return(out)
193}
194
195is_latex <- knitr::is_latex_output
196
197rmd_files_dir <- function(create = TRUE) {
198 curr_file_name <- sub("\\.[^\\.]*$", "", knitr::current_input())
199 dir_name <- paste0(curr_file_name, "_files")
200 if (!dir.exists(dir_name) & create) dir.create(dir_name)
Hao Zhu7f3fa852020-08-26 13:55:38 -0400201 fig_dir_name <- file.path(dir_name, "figure-latex/")
Hao Zhu5fe235c2020-08-26 00:26:49 -0400202 if (!dir.exists(fig_dir_name) & create) dir.create(fig_dir_name)
203 return(fig_dir_name)
204}
205
Hao Zhudefd1892020-09-09 00:08:09 -0400206#' Helper functions to generate inline sparklines
207#'
208#' @description These functions helps you quickly generate sets of sparkline
209#' style plots using base R plotting system. Currently, we support histogram,
210#' boxplot, and line. You can use them together with `column_spec` to
211#' generate inline plot in tables. By default, this function will save images
212#' in a folder called "kableExtra" and return the address of the file.
213#'
214#' @param x,y Vector of values or List of vectors of values. y is optional.
215#' @param width The width of the plot in pixel
216#' @param height The height of the plot in pixel
217#' @param res The resolution of the plot. Default is 300.
218#' @param same_lim T/F. If x is a list of vectors, should all the plots be
219#' plotted in the same range? Default is True.
220#' @param xlim,ylim Manually specify plotting range in the form of
221#' `c(0, 10)`.
222#' @param xaxt On/Off for xaxis text
223#' @param yaxt On/Off for yaxis text
224#' @param ann On/Off for annotations (titles and axis titles)
225#' @param col Color for the fill of the histogram bar/boxplot box.
226#' @param border Color for the border.
Bill Evans548d7152020-09-13 21:44:24 -0700227#' @param frame.plot On/Off for surrounding box (`spec_plot` only). Default
Hao Zhudefd1892020-09-09 00:08:09 -0400228#' is False.
Bill Evans548d7152020-09-13 21:44:24 -0700229#' @param lwd Line width for `spec_plot`; within `spec_plot`, the `minmax`
Hao Zhudefd1892020-09-09 00:08:09 -0400230#' argument defaults to use this value for `cex` for points. Default is 2.
Bill Evansa8ef1fb2020-09-12 22:55:46 -0700231#' @param pch,cex Shape and size for points (if type is other than "l").
232#' @param type Passed to `plot`, often one of "l", "p", or "b", see
233#' [graphics::plot.default()] for more details. Ignored when 'polymin' is
234#' not 'NA'.
235#' @param polymin Special argument that converts a "line" to a polygon,
236#' where the flat portion is this value, and the other side of the polygon
237#' is the 'y' value ('x' if no 'y' provided). If 'NA' (the default), then
Bill Evansad86c072020-09-13 21:54:52 -0700238#' this is ignored; otherwise if this is numeric then a polygon is
239#' created (and 'type' is ignored). Note that if 'polymin' is in the middle
240#' of the 'y' values, it will generate up/down polygons around this value.
Hao Zhudefd1892020-09-09 00:08:09 -0400241#' @param minmax,min,max Arguments passed to `points` to highlight minimum
Bill Evans548d7152020-09-13 21:44:24 -0700242#' and maximum values in `spec_plot`. If `min` or `max` are `NULL`, they
Hao Zhudefd1892020-09-09 00:08:09 -0400243#' default to the value of `minmax`. Set to an empty `list()` to disable.
244#' @param dir Directory of where the images will be saved.
245#' @param file File name. If not provided, a random name will be used
Bill Evansb62414a2020-09-14 12:33:38 -0700246#' @param file_type Graphic device. Can be character (e.g., `"pdf"`)
247#' or a graphics device function (`grDevices::pdf`). This defaults
248#' to `"pdf"` if the rendering is in LaTeX and `"svg"` otherwise.
Hao Zhudefd1892020-09-09 00:08:09 -0400249#' @param ... extra parameters passing to `plot`
250#'
Bill Evanscebc9712020-08-30 19:55:24 -0700251#' @export
Bill Evans548d7152020-09-13 21:44:24 -0700252spec_plot <- function(x, y = NULL, width = 200, height = 50, res = 300,
Bill Evanscebc9712020-08-30 19:55:24 -0700253 same_lim = TRUE, xlim = NULL, ylim = NULL,
254 xaxt = 'n', yaxt = 'n', ann = FALSE,
255 col = "lightgray", border = NULL,
256 frame.plot = FALSE, lwd = 2,
Bill Evansad86c072020-09-13 21:54:52 -0700257 pch = ".", cex = 2, type = "l", polymin = NA,
258 minmax = list(pch = ".", cex = cex, col = "red"),
Bill Evanscebc9712020-08-30 19:55:24 -0700259 min = minmax, max = minmax,
260 dir = if (is_latex()) rmd_files_dir() else tempdir(),
Bill Evansb62414a2020-09-14 12:33:38 -0700261 file = NULL, file_type = if (is_latex()) "pdf" else "svg", ...) {
Bill Evanscebc9712020-08-30 19:55:24 -0700262 if (is.list(x)) {
Bill Evans60fd80b2020-09-11 10:40:25 -0700263 lenx <- length(x)
264
Bill Evanscebc9712020-08-30 19:55:24 -0700265 if (same_lim) {
266 if (is.null(xlim)) {
Bill Evansad86c072020-09-13 21:54:52 -0700267 xlim <- base::range(unlist(x), na.rm = TRUE)
Bill Evanscebc9712020-08-30 19:55:24 -0700268 }
269 if (is.null(ylim) && !is.null(y)) {
Bill Evansad86c072020-09-13 21:54:52 -0700270 ylim <- base::range(c(unlist(y), polymin), na.rm = TRUE)
Bill Evanscebc9712020-08-30 19:55:24 -0700271 }
272 }
Bill Evansad86c072020-09-13 21:54:52 -0700273
Bill Evanscebc9712020-08-30 19:55:24 -0700274 if (is.null(y)) {
Bill Evansad86c072020-09-13 21:54:52 -0700275 y <- list(y)
276 } else if (length(y) != lenx) {
Bill Evanscebc9712020-08-30 19:55:24 -0700277 stop("'x' and 'y' are not the same length")
278 }
Bill Evans60fd80b2020-09-11 10:40:25 -0700279
Bill Evansb62414a2020-09-14 12:33:38 -0700280 dots <- listify_args(x, y = y, width, height, res,
281 xlim, ylim, xaxt, yaxt, ann, col, border, frame.plot,
282 lwd, pch, cex, type, polymin, minmax, min, max,
283 dir, file, file_type,
284 lengths = c(1, lenx))
Bill Evans60fd80b2020-09-11 10:40:25 -0700285
Bill Evans548d7152020-09-13 21:44:24 -0700286 return(do.call(Map, c(list(f = spec_plot), dots)))
Bill Evans60fd80b2020-09-11 10:40:25 -0700287
Bill Evanscebc9712020-08-30 19:55:24 -0700288 }
289
Bill Evans8def4da2020-09-11 09:58:26 -0700290 if (is.null(x)) return(NULL)
291
Bill Evanscebc9712020-08-30 19:55:24 -0700292 if (is.null(y) || !length(y)) {
293 y <- x
Bill Evansa8ef1fb2020-09-12 22:55:46 -0700294 x <- seq_along(y)
295 if (!is.null(xlim) && is.null(ylim)) {
Bill Evansad86c072020-09-13 21:54:52 -0700296 ylim <- range(c(xlim, polymin), na.rm = TRUE)
Bill Evansa8ef1fb2020-09-12 22:55:46 -0700297 xlim <- range(x)
298 }
Bill Evanscebc9712020-08-30 19:55:24 -0700299 }
300
301 if (is.null(xlim)) {
Bill Evansad86c072020-09-13 21:54:52 -0700302 xlim <- base::range(x, na.rm = TRUE)
Bill Evanscebc9712020-08-30 19:55:24 -0700303 }
304
305 if (is.null(ylim) && !is.null(y)) {
Bill Evansa8ef1fb2020-09-12 22:55:46 -0700306 ylim <- base::range(c(y, polymin), na.rm = TRUE)
Bill Evanscebc9712020-08-30 19:55:24 -0700307 }
308
309 if (is.null(min)) min <- minmax
310 if (is.null(max)) max <- minmax
311
312 expand <- c(
Bill Evans60fd80b2020-09-11 10:40:25 -0700313 if (!is.null(min) && length(min)) -0.04 else 0,
314 if (!is.null(max) && length(max)) +0.04 else 0)
315 xlim <- xlim + diff(xlim) * expand
316 ylim <- ylim + diff(ylim) * expand
Bill Evanscebc9712020-08-30 19:55:24 -0700317
Bill Evanscebc9712020-08-30 19:55:24 -0700318 if (!dir.exists(dir)) {
319 dir.create(dir)
320 }
321
Bill Evansb62414a2020-09-14 12:33:38 -0700322 file_ext <- dev_chr(file_type)
Bill Evanscebc9712020-08-30 19:55:24 -0700323 if (is.null(file)) {
Bill Evansb62414a2020-09-14 12:33:38 -0700324 file <- normalizePath(
325 tempfile(pattern = "plot_", tmpdir = dir, fileext = paste0(".", file_ext)),
326 winslash = "/", mustWork = FALSE)
Bill Evanscebc9712020-08-30 19:55:24 -0700327 }
328
Bill Evansb62414a2020-09-14 12:33:38 -0700329 graphics_dev(filename = file, dev = file_type,
330 width = width, height = height, res = res,
331 bg = "transparent")
Bill Evanscebc9712020-08-30 19:55:24 -0700332 curdev <- grDevices::dev.cur()
333 on.exit(grDevices::dev.off(curdev), add = TRUE)
334
Bill Evansa8ef1fb2020-09-12 22:55:46 -0700335 graphics::par(mar = c(0, 0, 0, 0), lwd = lwd)
336
337 dots <- list(...)
338 if (!is.na(polymin) && "angle" %in% names(dots)) {
339 angle <- dots$angle
340 dots$angle <- NULL
341 } else angle <- 45
342
343 do.call(graphics::plot,
344 c(list(x, y, type = if (is.na(polymin)) type else "n",
345 xlim = xlim, ylim = ylim,
Bill Evanscebc9712020-08-30 19:55:24 -0700346 xaxt = xaxt, yaxt = yaxt, ann = ann, col = col,
Bill Evansad86c072020-09-13 21:54:52 -0700347 frame.plot = frame.plot, cex = cex, pch = pch),
348 dots))
Bill Evansa8ef1fb2020-09-12 22:55:46 -0700349
350 if (!is.na(polymin)) {
351 lty <- if ("lty" %in% names(dots)) dots$lty else graphics::par("lty")
352 polygon(c(x[1], x, x[length(x)]), c(polymin, y, polymin),
Bill Evansad86c072020-09-13 21:54:52 -0700353 border = NA, col = col, angle = angle, lty = lty,
354 xpd = if ("xpd" %in% names(dots)) dots$xpd else NA)
Bill Evansa8ef1fb2020-09-12 22:55:46 -0700355 }
Bill Evanscebc9712020-08-30 19:55:24 -0700356
357 if (!is.null(min) && length(min)) {
Bill Evansad86c072020-09-13 21:54:52 -0700358 if (!"xpd" %in% names(min)) min$xpd <- NA
Bill Evanscebc9712020-08-30 19:55:24 -0700359 ind <- which.min(y)
Bill Evansad86c072020-09-13 21:54:52 -0700360 do.call(graphics::points, c(list(x[ind], y[ind]), min))
Bill Evanscebc9712020-08-30 19:55:24 -0700361 }
362
363 if (!is.null(max) && length(max)) {
Bill Evansad86c072020-09-13 21:54:52 -0700364 if (!"xpd" %in% names(max)) max$xpd <- NA
Bill Evanscebc9712020-08-30 19:55:24 -0700365 ind <- which.max(y)
Bill Evansad86c072020-09-13 21:54:52 -0700366 do.call(graphics::points, c(list(x[ind], y[ind]), max))
Bill Evanscebc9712020-08-30 19:55:24 -0700367 }
368
369 grDevices::dev.off(curdev)
370
Bill Evansb62414a2020-09-14 12:33:38 -0700371 out <- make_inline_plot(
372 file, file_ext, file_type,
373 width, height, res,
374 del = TRUE)
Bill Evanscebc9712020-08-30 19:55:24 -0700375 return(out)
376}