基于不同列的R数据表样式ColorBar

问题描述 投票:0回答:1

我想在我的数据表中有一个 styleColorBar,其中栏的大小基于不同的列。

iris %>% 
  select(Species, Petal.Length) %>% 
  group_by(Species) %>% 
  mutate(avg_petal = mean(Petal.Length)) %>% 
  datatable() %>% 
    formatStyle(
        'Petal.Length',
        background = styleColorBar(iris$Petal.Length, 'steelblue'),
        backgroundSize = '100% 90%',
        backgroundRepeat = 'no-repeat',
        backgroundPosition = 'center'
    )

如何在

Species
列的基础上向
avg_petal
列添加颜色条?

这可能吗?

r dt
1个回答
2
投票

您可以使用

valueColumns
参数,以便
datatable
知道数字列用于格式化,然后将格式化
data$avg_petal
传递给
styleColorBar

library(DT)

data <- iris %>% 
  select(Species, Petal.Length) %>% 
  group_by(Species) %>% 
  mutate(avg_petal = mean(Petal.Length))

data %>%  datatable() %>% 
  formatStyle(
    'Species', valueColumns = "avg_petal",
    background = styleColorBar(data$avg_petal, 'steelblue'),
    backgroundSize = '100% 90%',
    backgroundRepeat = 'no-repeat',
    backgroundPosition = 'center'
  )

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.