knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE)
library(reactablefmtr)
library(tidyverse)
library(gapminder)

With {reactablefmtr}, we can easily apply color tiles to columns within a table by using color_tiles() within cell of reactable::colDef().

By default a normalized orange-white-blue color scale is applied to each column.

data <- MASS::Cars93 %>% 
  filter(Type %in% c("Compact", "Sporty", "Van")) %>% 
  select(c("Make", "Type", "Horsepower", "MPG.city", "MPG.highway")) %>% 
  tail(10)

reactable(
  data,
  defaultColDef = colDef(
    cell = color_tiles(data)
  )
)

Custom color palettes

If we want to show a different color palette than the default, we can call them within the colors argument like so:

my_color_pal = c("#e5f5e0", "#a1d99b", "#31a354")

reactable(
  data,
  defaultColDef = colDef(
    cell = color_tiles(data, colors = my_color_pal)
  )
)

The opacity of the colors can be controlled by assigning a value between 0 (fully transparent) and 1 (fully opaque).

reactable(
  data,
  defaultColDef = colDef(
    cell = color_tiles(data, colors = my_color_pal, opacity = 0.5)
  )
)

The order of the color palette matters. In the example above, the color purple is assigned to the lowest values, lightgrey is assigned to middle values, and green is assigned to highest values.

We may also use color palettes from other packages, such as the "Mako" color palette from the {viridis} package:

library(viridis)

reactable(
  data,
  defaultColDef = colDef(
    cell = color_tiles(data, colors = viridis::mako(5))
  )
)

Adding a legend

If you would like to add a legend for the color palette used within color_tiles(), you can do so by including add_legend() below the table and listing the color palette used within color_tiles(). If no color palette is defined by the user within add_legend(), it will show the default blue-to-orange color palette used in color_tiles().

reactable(
  data,
  defaultColDef = colDef(
    cell = color_tiles(data, colors = viridis::mako(5))
  )
) %>% 
  add_legend(colors = viridis::mako(5))


By default, the labels next to the legend show as "Low" and "High". You can hide these labels by setting show_labels to FALSE or provide your own custom labels by providing one text label for the low values and one text label for the high values within labels as shown below:

reactable(
  data,
  defaultColDef = colDef(
    cell = color_tiles(data, colors = viridis::mako(5))
  )
) %>% 
  add_legend(colors = viridis::mako(5), labels = c("Low MPG", "High MPG"))


The position of the legend can be either "above" or "below" the table as specified with position, and the horizontal alignment can be either "left", "right", or "center" with align.

The margin around the legend can also be adjusted using margin and specifying the top, right, bottom, and left margin sizes in that order.

reactable(
  data,
  defaultColDef = colDef(
    cell = color_tiles(data, colors = viridis::mako(5))
  )
) %>% 
  add_legend(colors = viridis::mako(5), labels = c("Low MPG", "High MPG"), position = "above", align = "left", margin = margin(10, 0, 10, 0))

Formatting numbers

Numbers can be formatted within the number_fmt argument in color_tiles(). One method of formatting the numbers is by utilizing the formatters from the {scales} package, and the numbers can be formatted in the same way as they are in {ggplot2}.

reactable(
  data,
  columns = list(
    Horsepower = colDef(cell = color_tiles(data, number_fmt = scales::number_format(suffix = " hp"))),
    MPG.city = colDef(cell = color_tiles(data, number_fmt = scales::number_format(suffix = " mpg"))),
    MPG.highway = colDef(cell = color_tiles(data, number_fmt = scales::number_format(suffix = " mpg")))
  )
)

Adding a box shadow

Box shadows can be added to the tiles to create a "3-D" effect via box_shadow.

reactable(
  data,
  defaultColDef = colDef(
    cell = color_tiles(data,
                       box_shadow = TRUE)
  )
)

Assigning colors from another column

Colors can be conditionally assigned to values based on another column by using color_ref.

In the example below, we assigned a blue color to Compact cars, a red color to Sporty cars, and a gold color to Vans using dplyr::case_when().

Then within color_tiles(), we reference the name of the conditional column we just created to apply the colors to the values in MPG.city and MPG.highway.

car_data <- data %>% 
  mutate(car_colors = dplyr::case_when(
  Type == "Compact" ~ "dodgerblue",
  Type == "Sporty" ~ "tomato",
  Type == "Van" ~ "gold",
  TRUE ~ "other"
  ))

reactable(
  car_data,
  columns = list(
    Make = colDef(minWidth = 150),
    car_colors = colDef(show = FALSE),
    Horsepower = colDef(cell = color_tiles(car_data, color_ref = "car_colors")),
    MPG.city = colDef(cell = color_tiles(car_data, color_ref = "car_colors")),
    MPG.highway = colDef(cell = color_tiles(car_data, color_ref = "car_colors"))
  )
)

We can further apply the conditional colors to the entire dataset by setting the style within defaultColDef:

reactable(
  car_data,
    defaultColDef = colDef(
    cell = color_tiles(car_data, color_ref = "car_colors")
  ),
  columns = list(
    Make = colDef(minWidth = 150),
    car_colors = colDef(show = FALSE)
  )
)

The same conditional coloring can be applied based on numeric conditions as well. For example, if we wanted to highlight which cars have an MPG.city value of 23 or greater, we could use the same method as above but apply the conditions based on the MPG.city column instead of the Type column.

car_data <- car_data %>% 
  mutate(mpg_colors = dplyr::case_when(
  MPG.city >= 23 ~ "darkgreen",
  TRUE ~ "grey"
  ))

reactable(
  car_data,
  defaultSorted = "MPG.city",
  defaultSortOrder = "desc",
  defaultColDef = colDef(
    cell =color_tiles(car_data, color_ref = "mpg_colors")
    ),
  columns = list(
    Make = colDef(minWidth = 150),
    car_colors = colDef(show = FALSE),
    mpg_colors = colDef(show = FALSE))
)

Row-wise styling

By default, color_tiles() conditionally assigns colors to values based on their relation to other values within that particular column. However, if the table you're showing is row-wise data, such as average temperatures by month for each year, then it will be difficult to compare how temperatures compare in each month:

By including span = TRUE within our color_tiles() formatter, we can conditionally assign colors to the values based on their relation to other values within the entire dataset, instead of within each column. Now our table displaying temperatures is much easier to read when comparing temperatures across months:

Note: the dataset for this example is sourced from the reactable demo cookbook

dimnames <- list(start(nottem)[1]:end(nottem)[1], month.abb)
temps <- matrix(nottem, ncol = 12, byrow = TRUE, dimnames = dimnames)
temps <- as_tibble(temps, rownames = "Year")
temppal <- c("#36a1d6", "#76b8de", "#a0bfd9", "#ffffff", "#d88359", "#d65440", "#c62c34")

reactable(
  temps,
  defaultColDef = colDef(
    cell =color_tiles(temps, span = TRUE, colors = temppal),
    minWidth = 50
    )
)

If we only wanted to apply color tiles to some of the months, we can do so by referencing either the numeric positions of the columns or the column names within span:

reactable(
  temps,
  defaultColDef = colDef(
    cell =color_tiles(temps, span = 4:7, colors = temppal),
    minWidth = 50))

Lastly, if you wanted to completely hide the text, you could do this by setting show_text = FALSE, which displays the table as a heatmap as shown below:

Note: by setting tooltip = TRUE, the values are still visible on hover.

population_data <- gapminder %>% 
  filter(continent == "Americas") %>%
  mutate(country = as.character(country),
         year = paste0("'", str_sub(year, 3, 4))) %>% 
  select(country, year, lifeExp) %>%
  pivot_wider(names_from = year, values_from = lifeExp) 

reactable(
  population_data,
  compact = TRUE,
  pagination = FALSE,
  showSortIcon = FALSE,
  defaultSorted = "'52",
  defaultSortOrder = "desc",
  defaultColDef = colDef(
    maxWidth = 50,
    cell = color_tiles(population_data,
                       number_fmt = scales::comma,
                       show_text = FALSE, 
                       tooltip = TRUE, 
                       span = TRUE)
  ),
  columns = list(
    country = colDef(
      maxWidth = 175
    )
  )
) %>% 
  add_title("Average Life Expectancy") %>% 
  add_source("Data sourced from the {gapminder} package") 


kcuilla/reactablefmtr documentation built on Jan. 13, 2023, 11:36 p.m.