blob: f34715f0139cbcbd1ea0d3368aba34b75a2bc150 [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
4#' style plots using base R plotting system. Currently, we support histogram
5#' and boxplot. You can use them together with `column_spec` to
6#' 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.
15#' @param lim Manually specify plotting range in the form of `c(0, 10)`.
16#' @param xaxt On/Off for xaxis text
17#' @param yaxt On/Off for yaxis text
18#' @param ann On/Off for annotations (titles and axis titles)
19#' @param col Color for the fill of the histogram bar/boxplot box.
20#' @param border Color for the border.
21#' @param dir Directory of where the images will be saved.
22#' @param file File name. If not provided, a random name will be used
23#' @param file_type Graphic device. Support `png` or `svg`. SVG is recommended
24#' for HTML output
25#' @param add_label For boxplot. T/F to add labels for min, mean and max.
26#' @param label_digits If T for add_label, rounding digits for the label.
27#' Default is 2.
28#' @param boxlty Boxplot - box boarder type
29#' @param medcol Boxplot - median line color
30#' @param medlwd Boxplot - median line width
31#'
32#' @inheritParams graphics::hist
33#' @inheritParams graphics::boxplot
34#' @export
35spec_hist <- function(x, width = 200, height = 50, res = 300,
36 breaks = "Sturges",
37 same_lim = TRUE, lim = NULL,
38 xaxt = 'n', yaxt = 'n', ann = FALSE,
39 col = "lightgray", border = NULL,
40 dir = if (is_latex()) rmd_files_dir() else tempdir(),
41 file = NULL,
42 file_type = if (is_latex()) "png" else "svg", ...) {
43 if (is.list(x)) {
44 if (same_lim & is.null(lim)) {
45 lim <- base::range(unlist(x))
46 }
47 return(lapply(x, function(x_) {spec_hist(
48 x = x_, width = width, height = height,
49 breaks = breaks, same_lim = same_lim, lim = lim,
50 xaxt = xaxt, yaxt = yaxt, ann = ann, col = col, border = border,
51 dir = dir, file = file, file_type = file_type, ...
52 )}))
53 }
54
55 if (is.null(lim)) {
56 lim <- base::range(x)
57 }
58
59 file_type <- match.arg(file_type, c("svg", "png"))
60
61 if (!dir.exists(dir)) {
62 dir.create(dir)
63 }
64
65 if (is.null(file)) {
Hao Zhucd9a5812020-08-26 15:35:30 -040066 file <- file.path(dir, paste0(
67 "hist_", round(as.numeric(Sys.time()) * 1000), ".", file_type))
Hao Zhu5fe235c2020-08-26 00:26:49 -040068 }
69
70 if (file_type == "svg") {
71 grDevices::svg(filename = file, width = width / res, height = height / res,
72 bg = 'transparent')
73 } else {
74 grDevices::png(filename = file, width = width, height = height, res = res,
75 bg = 'transparent')
76 }
77
78 graphics::par(mar = c(0, 0, 0.2, 0), lwd=0.5)
79 graphics::hist(x, breaks = breaks, xlim = lim, border = border,
80 xaxt = xaxt, yaxt = yaxt, ann = ann, col = col, ...)
81 grDevices::dev.off()
82
83 if (file_type == "svg") {
84 svg_xml <- xml2::read_xml(file)
85 svg_text <- as.character(svg_xml)
86 unlink(file)
87 } else {
88 svg_text <- NULL
89 }
90 out <- list(path = file, dev = file_type, type = "hist",
91 width = width, height = height, res = res,
92 svg_text = svg_text)
93
94 class(out) <- "kableExtraInlinePlots"
95 return(out)
96}
97
98#' @rdname spec_hist
99#' @export
100spec_boxplot <- function(x, width = 200, height = 50, res = 300,
101 add_label = FALSE, label_digits = 2,
102 same_lim = TRUE, lim = NULL,
103 xaxt = 'n', yaxt = 'n', ann = FALSE,
104 col = "lightgray", border = NULL,
105 boxlty = 0, medcol = "red", medlwd = 1,
106 dir = if (is_latex()) rmd_files_dir() else tempdir(),
107 file = NULL,
108 file_type = if (is_latex()) "png" else "svg", ...) {
109 if (is.list(x)) {
110 if (same_lim & is.null(lim)) {
111 lim <- base::range(unlist(x))
112 }
113 return(lapply(x, function(x_) {spec_boxplot(
114 x = x_, width = width, height = height,
115 add_label = add_label, same_lim = same_lim, lim = lim,
116 xaxt = xaxt, yaxt = yaxt, ann = ann,
117 col = col, border = border,
118 boxlty = boxlty, medcol = medcol, medlwd = medlwd,
119 dir = dir, file = file, file_type = file_type, ...
120 )}))
121 }
122
123 if (is.null(lim)) {
124 lim <- base::range(x)
125 lim[1] <- lim[1] - (lim[2] - lim[1]) / 10
126 lim[2] <- (lim[2] - lim[1]) / 10 + lim[2]
127 }
128
129 file_type <- match.arg(file_type, c("svg", "png"))
130
131 if (!dir.exists(dir)) {
132 dir.create(dir)
133 }
134
135 if (is.null(file)) {
Hao Zhucd9a5812020-08-26 15:35:30 -0400136 file <- file.path(dir, paste0(
137 "hist_", round(as.numeric(Sys.time()) * 1000), ".", file_type))
Hao Zhu5fe235c2020-08-26 00:26:49 -0400138 }
139
140 if (file_type == "svg") {
141 grDevices::svg(filename = file, width = width / res, height = height / res,
142 bg = 'transparent')
143 } else {
144 grDevices::png(filename = file, width = width, height = height, res = res,
145 bg = 'transparent')
146 }
147
148 graphics::par(mar = c(0, 0, 0, 0))
149
150 graphics::boxplot(x, horizontal = TRUE, ann = ann, frame = FALSE, bty = 'n', ylim = lim,
151 col = col, border = border,
152 boxlty = boxlty, medcol = medcol, medlwd = medlwd,
153 axes = FALSE, outcex = 0.2, whisklty = 1,
154 ...)
155 if (add_label) {
156 x_median <- round(median(x, na.rm = T), label_digits)
157 x_min <- round(min(x, na.rm = T), label_digits)
158 x_max <- round(max(x, na.rm = T), label_digits)
159 graphics::text(x_median, y = 1.4, labels = x_median, cex = 0.5)
160 graphics::text(x_min, y = 0.6, labels = x_min, cex = 0.5)
161 graphics::text(x_max, y = 0.6, labels = x_max, cex = 0.5)
162 }
163 grDevices::dev.off()
164
165 if (file_type == "svg") {
166 svg_xml <- xml2::read_xml(file)
167 svg_text <- as.character(svg_xml)
168 unlink(file)
169 } else {
170 svg_text <- NULL
171 }
172 out <- list(path = file, dev = file_type, type = "boxplot",
173 width = width, height = height, res = res,
174 svg_text = svg_text)
175 class(out) <- "kableExtraInlinePlots"
176 return(out)
177}
178
179is_latex <- knitr::is_latex_output
180
181rmd_files_dir <- function(create = TRUE) {
182 curr_file_name <- sub("\\.[^\\.]*$", "", knitr::current_input())
183 dir_name <- paste0(curr_file_name, "_files")
184 if (!dir.exists(dir_name) & create) dir.create(dir_name)
Hao Zhu7f3fa852020-08-26 13:55:38 -0400185 fig_dir_name <- file.path(dir_name, "figure-latex/")
Hao Zhu5fe235c2020-08-26 00:26:49 -0400186 if (!dir.exists(fig_dir_name) & create) dir.create(fig_dir_name)
187 return(fig_dir_name)
188}
189