Customize colors in a kable table with kableExtra



This post explains how to customize colors in a kable output with kableExtra package. We’ll go through several examples to see how to add a color, several colors or a color gradient to a row or column with kableExtra.

Table Data to Viz

Packages


For this post, we need to load the following library:

library(kableExtra)


Dataset


We create a simple dataset with 3 columns to showcase the color features of kableExtra

df = data.frame(Temp = c(1,2,3,4),
                Rain = c(12, 42, 17, 9),
                Hum = c(21, 24, 71, 90)
                )

Default kable table output


The kableExtra relies on the kable package and allows the use of the %>% (pipe) symbole. The main function is named kbl() and is similar to kable().

df %>%
  kbl() %>%
  kable_styling()
Temp Rain Hum
1 12 21
2 42 24
3 17 71
4 9 90

Change color of a row or column


The row_spec() and column_spec() functions have a color and background arguments that will change the colors, either of the background or the cell content.

df %>%
  kbl(align = "c") %>% # center the columns
  kable_styling(full_width = F) %>%
  column_spec(2, color = "red") %>%
  row_spec(3, color = "blue") %>%
  column_spec(1, background = "green") %>%
  row_spec(4, background = "yellow")
Temp Rain Hum
1 12 21
2 42 24
3 17 71
4 9 90

Use a list of colors


The color and background argument can also takes a vector of colors:

df %>%
  kbl(align = "c") %>% # center the columns
  kable_styling(full_width = F) %>%
  column_spec(3, background = c("blue", "red", "black", "blue"))
Temp Rain Hum
1 12 21
2 42 24
3 17 71
4 9 90

Gradient of color


In order to have a gradient of colors, we need to use the colorRampPalette() function in order to generate a vector of colors.

We also sort the dataframe with the Rain column so that the colors will be proportional to the values in this column.

# gradient color
colfunc = colorRampPalette(c("darkred", "magenta"))
n_color = nrow(df)
colors = colfunc(n_color) # generate nrow(df) (number of rows in df) colors, from darkred to magenta

df = df[order(df$Rain, decreasing = TRUE),] # sort (decreasing) by Rain values

df %>%
  kbl(align = "c") %>% # center the columns
  kable_styling(full_width = F) %>%
  column_spec(3, background = colors) %>%
  column_spec(2, color = colors)
Temp Rain Hum
2 2 42 24
3 3 17 71
1 1 12 21
4 4 9 90

Conclusion

This post explained how to custom colors in a table using the kableExtra library. For more of this package, see the dedicated section or the table section.

Related chart types


Line plot
Area
Stacked area
Streamchart
Time Series



Contact

This document is a work by Yan Holtz. Any feedback is highly encouraged. You can fill an issue on Github, drop me a message on Twitter, or send an email pasting yan.holtz.data with gmail.com.