Setting background colour for a cell in Rstudio gt package

时间:2019-02-18 00:51:15

标签: r colors cut

Using the data_color function in the gt package, I'd like to set up custom colors for a continuous distribution using non-equal ranges. cut() organizes the data correctly (outside of gt), but when using scale::col_bins() as an argument to data_color(), my code fails, producing no colours:

library(tidyverse)
library(gt)
diamonds %>% select(color, price) %>% group_by(color) %>% summarise(meanprice=mean(price))-> junk

junk$cutprice <- cut(junk$meanprice, breaks=c(3000, 3500, 4000,     5000, 10000), labels=FALSE)


junk %>% select(-cutprice) %>%  gt() %>% 
      data_color(columns=var(meanprice),
                 color=scales::col_bin(
                    bins=c(3000, 3500, 4000, 5000, 10000),
                    palette = c("red", "orange", "green", "blue", "black"),
                    domain=c(2000, 8000))
        )

The initial use of base::cut() works fine, but my syntax for the col_bin argument to data color is clearly failing. Suggestions on alternative syntax. I could not find an example of scale::col_bins() to address this situation.

Many thanks,

1 个答案:

答案 0 :(得分:0)

library(tidyverse)
library(gt)
diamonds %>% select(color, price) %>% group_by(color) %>% summarise(meanprice=mean(price))-> junk

junk$cutprice <- cut(junk$meanprice, breaks=c(3000, 3500, 4000,     5000, 10000), labels=FALSE)


junk %>% select(-cutprice) %>%  gt() %>% 
  data_color(columns=vars(meanprice), ### Changed 'var' to 'vars'
             color=scales::col_bin(
               bins=c(3000, 3500, 4000, 5000, 10000),
               palette = c("red", "orange", "green", "blue", "black"),
               domain=c(2000, 8000))
  )