Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map cell colors to data values in kableExtra to create a heatmap table

I have a table below and would like to apply ROW-level heat maps.

(1) Any idea how? Right now the heat map is the same for both values in the single row below.

(2) Is there a way to make the header for the group column NOT be angled 90 degrees? Right now all headers are angled but for the group column it be better without angle=90.

here is the rmd file.

---
title: "Untitled"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)


library(dplyr)
library(kableExtra)
#d = data.frame(group= c("A","b"),cat1=c(2,50),cat2=c(100,2))
d = data.frame(group= c("A"),cat1=c(2),cat2=c(NA))

d = d %>%
    mutate_if(is.numeric, function(x) {
  cell_spec(x, "latex", bold = F, background = spec_color(x,option="C", begin=.5, end = 0.99))
}) 

```



```{r table , echo= FALSE, comment = FALSE, message= FALSE, warning = FALSE, fig.height=3, fig.width = 8} 

kable(
      d, format ="latex",
      caption = "",
      booktabs = T, 
      longtable = T,
      escape = F ,
      align = "c"
      ) %>% kable_styling(latex_options = c(
        "striped", 
        "repeat_header"
        )
       )%>% row_spec( 0,angle = 90)


```

Note: Ideally it'd be good to have this done with the kableExtra functionality so they color schemes match exactley to other kableExtra tables.

like image 233
user3022875 Avatar asked Oct 26 '25 20:10

user3022875


1 Answers

I'm actually not sure how to get the desired color mapping from spec_color. As an alternative, in the code below I've generated the color mapping using the colorRamp function and a palette-generating function, which can be adjusted as desired. The code also deals with missing values by coloring them light gray.

---
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(viridis)
library(dplyr)
library(kableExtra)

set.seed(2)
d = data_frame(group = sample(LETTERS[1:5], 10, replace=TRUE), cat1=runif(10, 0, 100), cat2=runif(10, 0, 100))
d[5,2] = NA

max.val = max(d[ , sapply(d, is.numeric)], na.rm=TRUE)

#pal.fnc = colorRamp(viridis_pal(option="C")(2))
pal.fnc = colorRamp(c("red", "yellow", "green"))

d = d %>%
    mutate_if(is.numeric, function(x) {
  cell_spec(round(x,1), "latex", bold = F, color=grey(.3),
            background = rgb(pal.fnc(x/max.val) %>% replace(., is.na(.), 200), maxColorValue=255))
}) 

```

```{r table , echo= FALSE, comment = FALSE, message= FALSE, warning = FALSE, fig.height=3, fig.width = 8} 
kable(
      d, format ="latex",
      linesep="",
      caption = "",
      booktabs = T, 
      longtable = T,
      escape = F ,
      align = "c"
      ) %>% kable_styling(latex_options = c(
        "striped", 
        "repeat_header"
        )
       )
```

enter image description here

like image 80
eipi10 Avatar answered Oct 28 '25 11:10

eipi10