added spec_image, spec_hist, spec_boxplot and fixed some cran comments
diff --git a/R/column_spec.R b/R/column_spec.R
index fd33b4e..bdc8655 100644
--- a/R/column_spec.R
+++ b/R/column_spec.R
@@ -51,6 +51,7 @@
#' to build a popover is through `spec_popover()`. If you only provide a text
#' string, it will be used as content. Note that You have to enable this
#' bootstrap module manually. Read the package vignette to see how.
+#' @param image Vector of image paths.
#'
#' @details Use `latex_column_spec` in a LaTeX table to change or
#' customize the column specification. Because of the way it is handled
@@ -70,7 +71,7 @@
extra_css = NULL, include_thead = FALSE,
latex_column_spec = NULL, latex_valign = 'p',
link = NULL, new_tab = TRUE,
- tooltip = NULL, popover = NULL) {
+ tooltip = NULL, popover = NULL, image = NULL) {
if (!is.numeric(column)) {
stop("column must be numeric. ")
}
@@ -89,7 +90,7 @@
border_left, border_right,
width_min, width_max,
extra_css, include_thead,
- link, new_tab, tooltip, popover))
+ link, new_tab, tooltip, popover, image))
}
if (kable_format == "latex") {
return(column_spec_latex(kable_input, column, width,
@@ -98,7 +99,7 @@
color, background,
border_left, border_right,
latex_column_spec, latex_valign, include_thead,
- link))
+ link, image))
}
}
@@ -109,7 +110,7 @@
border_left, border_right,
width_min, width_max,
extra_css, include_thead,
- link, new_tab, tooltip, popover) {
+ link, new_tab, tooltip, popover, image) {
kable_attrs <- attributes(kable_input)
kable_xml <- read_kable_as_xml(kable_input)
kable_tbody <- xml_tpart(kable_xml, "tbody")
@@ -163,6 +164,7 @@
new_tab <- ensure_len_html(new_tab, nrows, "new_tab")
tooltip <- ensure_len_html(tooltip, nrows, "tooltip")
popover <- ensure_len_html(popover, nrows, "popover")
+ image <- ensure_len_html(image, nrows, "image")
for (i in all_contents_rows) {
for (j in column) {
@@ -173,7 +175,7 @@
color[i], background[i], border_left, border_right,
border_l_css, border_r_css,
extra_css,
- link[i], new_tab[i], tooltip[i], popover[i]
+ link[i], new_tab[i], tooltip[i], popover[i], image[i]
)
}
}
@@ -199,7 +201,7 @@
border_left, border_right,
border_l_css, border_r_css,
extra_css,
- link, new_tab, tooltip, popover) {
+ link, new_tab, tooltip, popover, image) {
if (is.na(xml_attr(target_cell, "style"))) {
xml_attr(target_cell, "style") <- ""
}
@@ -259,6 +261,24 @@
extra_css)
}
+ if (!is.null(image)) {
+ image <- image[[1]]
+ if (class(image) == "kableExtraInlinePlots") {
+ if (!is.null(image$svg_text)) {
+ xml_add_child(target_cell, xml2::read_xml(image$svg_text))
+ } else {
+ img_text <- paste0('<img src="', image$path, '" width="',
+ image$width / image$res * 96, '" height="',
+ image$height / image$res * 96,
+ '"></img>')
+ xml_add_child(target_cell, xml2::read_html(img_text))
+ }
+ } else {
+ img_text <- paste0('<img src="', image, '"></img>')
+ xml_add_child(target_cell, xml2::read_html(img_text))
+ }
+ }
+
# favor popover over tooltip
if (!is.null(popover)) {
if (class(popover) != "ke_popover") popover <- spec_popover(popover)
@@ -273,29 +293,6 @@
xml_attr(target_cell, t) <- tooltip_list[t]
}
}
- # if (!is.null(popover)) {
- # if (class(popover) != "ke_popover") popover <- spec_popover(popover)
- # popover_list <- attr(popover, 'list')
- # span_node <- xml2::read_xml(paste0(
- # '<span>', xml_text(target_cell), '</span>'
- # ))
- # for (p in names(popover_list)) {
- # xml_attr(span_node, p) <- popover_list[p]
- # }
- # xml_add_child(target_cell, span_node)
- # xml_text(target_cell) <- ""
- # } else if (!is.null(tooltip)) {
- # if (class(tooltip) != "ke_tooltip") tooltip <- spec_tooltip(tooltip)
- # tooltip_list <- attr(tooltip, 'list')
- # span_node <- xml2::read_xml(paste0(
- # '<span>', xml_text(target_cell), '</span>'
- # ))
- # for (t in names(tooltip_list)) {
- # xml_attr(span_node, t) <- tooltip_list[t]
- # }
- # xml_add_child(target_cell, span_node)
- # xml_text(target_cell) <- ""
- # }
if (!is.null(link)) {
href_node <- xml2::read_xml(paste0(
@@ -316,7 +313,7 @@
color, background,
border_left, border_right,
latex_column_spec, latex_valign, include_thead,
- link) {
+ link, image) {
table_info <- magic_mirror(kable_input)
if (!is.null(table_info$collapse_rows)) {
message("Usually it is recommended to use column_spec before collapse_rows,",
@@ -368,6 +365,7 @@
background <- ensure_len_latex(background, nrows, off, include_thead, "white",
"background")
link <- ensure_len_latex(link, nrows, off, include_thead, "#", "link")
+ image <- ensure_len_latex(image, nrows, off, include_thead, "", "image")
if (include_thead) {
rows <- seq(1, nrows)
@@ -380,7 +378,7 @@
new_row <- latex_cell_builder(
target_row, column, table_info,
bold[i], italic[i], monospace[i], underline[i],
- strikeout[i], color[i], background[i], link[i]
+ strikeout[i], color[i], background[i], link[i], image[i]
# font_size, angle
)
temp_sub <- ifelse(i == 1 & (table_info$tabular == "longtable" |
@@ -494,7 +492,7 @@
latex_cell_builder <- function(target_row, column, table_info,
bold, italic, monospace,
underline, strikeout,
- color, background, link
+ color, background, link, image
# font_size, angle
) {
new_row <- latex_row_cells(target_row)[[1]]
@@ -538,6 +536,30 @@
new_row[column], "\\}")
}
+ if (!is.null(image)) {
+ image <- image[[1]]
+ if (class(image) == "kableExtraInlinePlots") {
+ new_row[column] <- paste0(
+ new_row[column],
+ '\\\\includegraphics\\[width=',
+ # '\\\\raisebox\\{-\\\\totalheight\\}\\{\\\\includegraphics\\[width=',
+ round(image$width / image$res, 2), 'in, height=',
+ round(image$height / image$res, 2), 'in\\]\\{',
+ image$path,
+ '\\}'
+ # '\\}\\}'
+ )
+ } else {
+ if (!is.null(image) && !is.na(image) && image != "") {
+ new_row[column] <- paste0(
+ new_row[column],
+ '\\\\includegraphics\\{',
+ image, '\\}'
+ )
+ }
+ }
+ }
+
new_row <- paste(new_row, collapse = " & ")
return(new_row)
diff --git a/R/kableExtra-package.R b/R/kableExtra-package.R
index 35617e1..415b5b0 100644
--- a/R/kableExtra-package.R
+++ b/R/kableExtra-package.R
@@ -68,13 +68,14 @@
#' @importFrom utils read.csv head capture.output
#' @importFrom scales rescale
#' @importFrom viridisLite viridis
-#' @importFrom stats ave
-#' @importFrom grDevices col2rgb
+#' @importFrom stats ave density median
+#' @importFrom grDevices col2rgb svg png
#' @importFrom rstudioapi isAvailable viewer
#' @importFrom glue glue
#' @importFrom tools file_ext file_path_sans_ext
#' @importFrom webshot webshot
#' @importFrom digest digest
+#' @importFrom graphics par text hist boxplot
#' @import htmltools
#' @name kableExtra-package
#' @aliases kableExtra
diff --git a/R/light_themes.R b/R/light_themes.R
index e4ed2a3..a37e541 100644
--- a/R/light_themes.R
+++ b/R/light_themes.R
@@ -35,7 +35,7 @@
#' @export
kable_minimal <- function(
kable_input, lightable_options = "basic",
- html_font = '"Trebuchet MS", verdana, calibri, sans-serif', ...) {
+ html_font = '"Trebuchet MS", verdana, sans-serif', ...) {
kable_light(kable_input, "lightable-minimal",
lightable_options, html_font, ...)
}
diff --git a/R/mini_plots.R b/R/mini_plots.R
new file mode 100644
index 0000000..f6ed31d
--- /dev/null
+++ b/R/mini_plots.R
@@ -0,0 +1,187 @@
+#' Helper functions to generate inline sparklines
+#'
+#' @description These functions helps you quickly generate sets of sparkline
+#' style plots using base R plotting system. Currently, we support histogram
+#' and boxplot. You can use them together with `column_spec` to
+#' generate inline plot in tables. By default, this function will save images
+#' in a folder called "kableExtra" and return the address of the file.
+#'
+#' @param x Vector of values or List of vectors of values.
+#' @param width The width of the plot in pixel
+#' @param height The height of the plot in pixel
+#' @param res The resolution of the plot. Default is 300.
+#' @param same_lim T/F. If x is a list of vectors, should all the plots be
+#' plotted in the same range? Default is True.
+#' @param lim Manually specify plotting range in the form of `c(0, 10)`.
+#' @param xaxt On/Off for xaxis text
+#' @param yaxt On/Off for yaxis text
+#' @param ann On/Off for annotations (titles and axis titles)
+#' @param col Color for the fill of the histogram bar/boxplot box.
+#' @param border Color for the border.
+#' @param dir Directory of where the images will be saved.
+#' @param file File name. If not provided, a random name will be used
+#' @param file_type Graphic device. Support `png` or `svg`. SVG is recommended
+#' for HTML output
+#' @param add_label For boxplot. T/F to add labels for min, mean and max.
+#' @param label_digits If T for add_label, rounding digits for the label.
+#' Default is 2.
+#' @param boxlty Boxplot - box boarder type
+#' @param medcol Boxplot - median line color
+#' @param medlwd Boxplot - median line width
+#'
+#' @inheritParams graphics::hist
+#' @inheritParams graphics::boxplot
+#' @export
+spec_hist <- function(x, width = 200, height = 50, res = 300,
+ breaks = "Sturges",
+ same_lim = TRUE, lim = NULL,
+ xaxt = 'n', yaxt = 'n', ann = FALSE,
+ col = "lightgray", border = NULL,
+ dir = if (is_latex()) rmd_files_dir() else tempdir(),
+ file = NULL,
+ file_type = if (is_latex()) "png" else "svg", ...) {
+ if (is.list(x)) {
+ if (same_lim & is.null(lim)) {
+ lim <- base::range(unlist(x))
+ }
+ return(lapply(x, function(x_) {spec_hist(
+ x = x_, width = width, height = height,
+ breaks = breaks, same_lim = same_lim, lim = lim,
+ xaxt = xaxt, yaxt = yaxt, ann = ann, col = col, border = border,
+ dir = dir, file = file, file_type = file_type, ...
+ )}))
+ }
+
+ if (is.null(lim)) {
+ lim <- base::range(x)
+ }
+
+ file_type <- match.arg(file_type, c("svg", "png"))
+
+ if (!dir.exists(dir)) {
+ dir.create(dir)
+ }
+
+ if (is.null(file)) {
+ file <- tempfile("hist", dir, paste0('.', file_type))
+ }
+
+ if (file_type == "svg") {
+ grDevices::svg(filename = file, width = width / res, height = height / res,
+ bg = 'transparent')
+ } else {
+ grDevices::png(filename = file, width = width, height = height, res = res,
+ bg = 'transparent')
+ }
+
+ graphics::par(mar = c(0, 0, 0.2, 0), lwd=0.5)
+ graphics::hist(x, breaks = breaks, xlim = lim, border = border,
+ xaxt = xaxt, yaxt = yaxt, ann = ann, col = col, ...)
+ grDevices::dev.off()
+
+ if (file_type == "svg") {
+ svg_xml <- xml2::read_xml(file)
+ svg_text <- as.character(svg_xml)
+ unlink(file)
+ } else {
+ svg_text <- NULL
+ }
+ out <- list(path = file, dev = file_type, type = "hist",
+ width = width, height = height, res = res,
+ svg_text = svg_text)
+
+ class(out) <- "kableExtraInlinePlots"
+ return(out)
+}
+
+#' @rdname spec_hist
+#' @export
+spec_boxplot <- function(x, width = 200, height = 50, res = 300,
+ add_label = FALSE, label_digits = 2,
+ same_lim = TRUE, lim = NULL,
+ xaxt = 'n', yaxt = 'n', ann = FALSE,
+ col = "lightgray", border = NULL,
+ boxlty = 0, medcol = "red", medlwd = 1,
+ dir = if (is_latex()) rmd_files_dir() else tempdir(),
+ file = NULL,
+ file_type = if (is_latex()) "png" else "svg", ...) {
+ if (is.list(x)) {
+ if (same_lim & is.null(lim)) {
+ lim <- base::range(unlist(x))
+ }
+ return(lapply(x, function(x_) {spec_boxplot(
+ x = x_, width = width, height = height,
+ add_label = add_label, same_lim = same_lim, lim = lim,
+ xaxt = xaxt, yaxt = yaxt, ann = ann,
+ col = col, border = border,
+ boxlty = boxlty, medcol = medcol, medlwd = medlwd,
+ dir = dir, file = file, file_type = file_type, ...
+ )}))
+ }
+
+ if (is.null(lim)) {
+ lim <- base::range(x)
+ lim[1] <- lim[1] - (lim[2] - lim[1]) / 10
+ lim[2] <- (lim[2] - lim[1]) / 10 + lim[2]
+ }
+
+ file_type <- match.arg(file_type, c("svg", "png"))
+
+ if (!dir.exists(dir)) {
+ dir.create(dir)
+ }
+
+ if (is.null(file)) {
+ file <- tempfile("hist", dir, paste0('.', file_type))
+ }
+
+ if (file_type == "svg") {
+ grDevices::svg(filename = file, width = width / res, height = height / res,
+ bg = 'transparent')
+ } else {
+ grDevices::png(filename = file, width = width, height = height, res = res,
+ bg = 'transparent')
+ }
+
+ graphics::par(mar = c(0, 0, 0, 0))
+
+ graphics::boxplot(x, horizontal = TRUE, ann = ann, frame = FALSE, bty = 'n', ylim = lim,
+ col = col, border = border,
+ boxlty = boxlty, medcol = medcol, medlwd = medlwd,
+ axes = FALSE, outcex = 0.2, whisklty = 1,
+ ...)
+ if (add_label) {
+ x_median <- round(median(x, na.rm = T), label_digits)
+ x_min <- round(min(x, na.rm = T), label_digits)
+ x_max <- round(max(x, na.rm = T), label_digits)
+ graphics::text(x_median, y = 1.4, labels = x_median, cex = 0.5)
+ graphics::text(x_min, y = 0.6, labels = x_min, cex = 0.5)
+ graphics::text(x_max, y = 0.6, labels = x_max, cex = 0.5)
+ }
+ grDevices::dev.off()
+
+ if (file_type == "svg") {
+ svg_xml <- xml2::read_xml(file)
+ svg_text <- as.character(svg_xml)
+ unlink(file)
+ } else {
+ svg_text <- NULL
+ }
+ out <- list(path = file, dev = file_type, type = "boxplot",
+ width = width, height = height, res = res,
+ svg_text = svg_text)
+ class(out) <- "kableExtraInlinePlots"
+ return(out)
+}
+
+is_latex <- knitr::is_latex_output
+
+rmd_files_dir <- function(create = TRUE) {
+ curr_file_name <- sub("\\.[^\\.]*$", "", knitr::current_input())
+ dir_name <- paste0(curr_file_name, "_files")
+ if (!dir.exists(dir_name) & create) dir.create(dir_name)
+ fig_dir_name <- file.path(dir_name, "figure-latex")
+ if (!dir.exists(fig_dir_name) & create) dir.create(fig_dir_name)
+ return(fig_dir_name)
+}
+
diff --git a/R/spec_tools.R b/R/spec_tools.R
index 350925b..4537ada 100644
--- a/R/spec_tools.R
+++ b/R/spec_tools.R
@@ -164,3 +164,36 @@
attr(popover_options, 'list') <- popover_options_list
return(popover_options)
}
+
+#' Setup image path, size, etc
+#'
+#' @description Users can directly provide image file path to column spec.
+#' However, if you need to specify the size of the image, you will need this
+#' function.
+#'
+#' @param path file path(s)
+#' @param width image width in pixel
+#' @param height image height in pixel
+#' @param res image resolution.
+#' @param svg_text If you have the raw text for SVG. Put them here
+#'
+#' @export
+spec_image <- function(path, width, height, res = 300, svg_text = NULL) {
+ if (length(path) > 1) {
+ return(lapply(path, function(p) {
+ return(spec_image(p, width, height, res, svg_text))
+ }))
+ }
+ if (!is.null(svg_text)) {
+ out <- list(path = NULL, dev = NULL, type = "image",
+ width = NULL, height = NULL, res = NULL,
+ svg_text = svg_text)
+ class(out) <- "kableExtraInlinePlots"
+ return(out)
+ }
+ out <- list(path = path, dev = "external", type = "image",
+ width = width, height = height, res = res,
+ svg_text = svg_text)
+ class(out) <- "kableExtraInlinePlots"
+ return(out)
+}