Skip to contents

The gt_plt_bar_pct function takes an existing gt_tbl object and adds horizontal barplots via native HTML. This is a wrapper around raw HTML strings, gt::text_transform() and gt::cols_align(). Note that values default to being normalized to the percent of the maximum observed value in the specified column. You can turn this off if the values already represent a percentage value representing 0-100.

Usage

gt_plt_bar_pct(
  gt_object,
  column,
  height = 16,
  fill = "purple",
  background = "#e1e1e1",
  scaled = FALSE
)

Arguments

gt_object

An existing gt table object of class gt_tbl

column

The column wherein the bar plot should replace existing data.

height

A number representing the vertical height of the plot in pixels. Defaults to 16 px.

fill

A character representing the fill for the bar, defaults to purple. Accepts a named color (eg 'purple') or a hex color.

background

A character representing the background filling out the 100% mark of the bar, defaults to light grey. Accepts a named color (eg 'white') or a hex color.

scaled

TRUE/FALSE logical indicating if the value is already scaled to a percent of max (TRUE) or if it needs to be scaled (FALSE). Defaults to FALSE, meaning the value will be divided by the max value in that column and then multiplied by 100.

Value

An object of class gt_tbl.

Examples

library(gt)
 gt_bar_plot_tab <- mtcars %>%
   head() %>%
   dplyr::select(cyl, mpg) %>%
   dplyr::mutate(mpg_pct_max = round(mpg/max(mpg) * 100, digits = 2),
                 mpg_scaled = mpg/max(mpg) * 100) %>%
   dplyr::mutate(mpg_unscaled = mpg) %>%
   gt() %>%
   gt_plt_bar_pct(column = mpg_scaled, scaled = TRUE) %>%
   gt_plt_bar_pct(column = mpg_unscaled, scaled = FALSE,
                  fill = "blue", background = "lightblue") %>%
   cols_align("center", contains("scale")) %>%
   cols_width(4 ~ px(125),
              5 ~ px(125))

Figures

Function ID

3-5