简体   繁体   English

gt R 表格 - 根据一列中的值为整行着色

[英]gt R Tables - Colour entire rows based on values in one column

I'd like to colour an entire row based on the values in one column using the R package gt.我想使用 R package gt 根据一列中的值为整行着色。 What I'd like is shown below, where rows are red for the smallest values of mpg, and blue for the highest values.我想要的如下所示,其中行为红色表示 mpg 的最小值,蓝色表示最高值。

mtcars 表,其中行由 mpg 列中的值着色

Using the code below:使用下面的代码:

mtcars |> 
  head() |> 
  select(mpg, cyl, disp, drat) |> 
  gt() |> 
  data_color(
    columns = mpg,
    colors = scales::col_numeric(
      palette = c("red", "orange", "green", "blue"),
    domain = c(18, 23))
  )

Gives the right behaviour only for the mpg column itself.仅为 mpg 列本身提供正确的行为。

gt 表只有一列彩色

One option would be to create breaks, then use that for the rows argument in tab_style rather than using data_color (which doesn't have a rows argument).一种选择是创建中断,然后将其用于tab_style中的 rows 参数,而不是使用data_color (没有 rows 参数)。 Here, I set the breaks using cut , but you could use something like ntile to break up into groups (commented out below).在这里,我使用cut设置中断,但您可以使用ntile类的东西分成组(在下面注释掉)。

library(tidyverse)
library(gt)

mtcars |>
  head() |>
  select(mpg, cyl, disp, drat) |>
  #mutate(breaks = ntile(mpg, 4)) |>
  mutate(breaks = cut(mpg, breaks = c(0, 18.2, 18.8, 21.5, 30), right = T, labels = F)) |>
  gt() |>
  tab_style(
    style = cell_fill(color = "red"),
    locations = cells_body(
      rows = breaks == 1)
  ) |>
  tab_style(
    style = cell_fill(color = "orange"),
    locations = cells_body(
      rows = breaks == 2)
  ) |>
  tab_style(
    style = cell_fill(color = "green"),
    locations = cells_body(
      rows = breaks == 3)
  ) |>
  tab_style(
    style = cell_fill(color = "blue"),
    locations = cells_body(
      rows = breaks == 4)
  )

Output Output

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM