Using palettes with gt

# Preview vignette with: devtools::build_rmd("vignettes/gt.Rmd")
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

This vignette shows you how to use palettes to colour data cells with gt.

library(palettes)
library(gt)
library(scales)
library(dplyr)

Preparing the table

To demonstrate how to use palettes to colour data cells with gt, we will use airquality as an input data table with the following columns:

Temperature is a good fit for colour---we can represent cold with blue and hot with red.

First we create the gt table we will add colour to. The table is slightly modified from a table in the Introduction to Creating gt Tables article. It looks like this.

# Modify the `airquality` dataset by adding the year
# of the measurements (1973) and limiting to 10 rows
airquality_m <- 
  airquality %>%
  mutate(Year = 1973L) %>%
  slice(1:10) %>% 
  select(Year, Month, Day, Temp)

# Create a display table using the `airquality`
# dataset; arrange columns into groups
gt_tbl <- 
  gt(airquality_m) %>%
  tab_header(
    title = "New York Temperature Measurements",
    subtitle = "Daily measurements in New York City (May 1-10, 1973)"
  ) %>%
  tab_spanner(
    label = "Time",
    columns = c(Year, Month, Day)
  ) %>%
  tab_spanner(
    label = "Measurement",
    columns = c(Temp)
  ) %>%
  cols_label(
    Temp = html("Temp,<br>&deg;F")
  )

# Show the gt table
gt_tbl

Adding colour

We can use the Hiroshige palette for blue and red gradients, reversing it so the colours are in the correct order for this example.

colour_vector <- rev(met_palettes$Hiroshige)
colour_vector

At the moment, objects of class palettes_palette or palettes_colour cannot be used directly with the colour functions in gt. To work around this we cast the colour vector to a character vector.

character_vector <- as.character(colour_vector)
character_vector

Now we can use gt::data_color() to colour the temperature cells. The colors argument accepts either a vector of colours to use for each distinct cell value or level or a colour mapping function (e.g., from the scales package).

Here we pass the character vector directly to the colors argument.

gt_tbl %>% 
  data_color(
    columns = Temp,
    palette = character_vector
  )

But this works equally well with the colour mapping functions from palettes.

gt_tbl %>% 
  data_color(
    columns = Temp,
    fn = pal_numeric(colour_vector, domain = NULL)
  )

The colour mapping functions from palettes are: pal_numeric(), pal_bin(), pal_quantile(), and pal_factor(). These functions are useful when you need finer control over colour evaluation with data.



Try the palettes package in your browser

Any scripts or data that you put into this service are public.

palettes documentation built on Sept. 11, 2024, 5:57 p.m.