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.
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()
.
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.
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 |
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.
👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥