table 在 R 中的条件格式......更好的方法?

Conditional formatting of table in R...a better way?

正在尝试改进此代码。我所做的工作有效,但看起来很难看,而且非常笨拙。

正在寻找 ggplot 方法或对用户更友好的方法。将不胜感激提示和建议。

library("dplyr")
thi <- data.frame(RH    = c(1,1,1,2,2,2,3,3,3), T = c(1,2,3,1,2,3,1,2,3), THI = c(8,8,5,7,5,10,5,8,7))
table_thi <- tapply(thi$THI, list(thi$RH, thi$T), mean) %>% as.table()

x = 1:ncol(table_thi)
y = 1:nrow(table_thi)
centers <- expand.grid(y,x)

image(x, y, t(table_thi),
  col = c("lightgoldenrod", "darkgoldenrod", "darkorange"),
  breaks = c(5,7,8,9),
  xaxt = 'n', 
  yaxt = 'n', 
  xlab = '', 
  ylab = '',
  ylim = c(max(y) + 0.5, min(y) - 0.5))

text(round(centers[,2],0), round(centers[,1],0), c(table_thi), col= "black")

mtext(paste(attributes(table_thi)$dimnames[[2]]), at=1:ncol(table_thi), padj = -1)
mtext(attributes(table_thi)$dimnames[[1]], at=1:nrow(table_thi), side = 2, las = 1, adj = 1.2)

abline(h=y + 0.5)
abline(v=x + 0.5)

这个怎么样:

library(dplyr)
library(ggplot2)
thi <- data.frame(
   RH = c(1, 1, 1, 2, 2, 2, 3, 3, 3), 
    T = c(1, 2, 3, 1, 2, 3, 1, 2, 3), 
  THI = c(8, 8, 5, 7, 5, 10, 5, 8, 7)
)

names(thi) = c('col1', 'col2', 'thi')

ggplot(thi, aes(x = col1, y = col2, fill = factor(thi), label = thi)) +
  geom_tile() +
  geom_text()

或者根据 thi 是真正的 factor(离散)还是连续变量,您可能需要这样的东西:

ggplot(thi, aes(x = col1, y = col2, fill = thi, label = thi)) +
  geom_tile() +
  geom_text(color = 'white')

注意:您可能希望避免使用作为保留字或缩写的列名或变量名(例如,避免调用某些内容 T,因为那是关键字 TRUE 的缩写).在上面的代码中,我重命名了 data.frame.

的列

由于问题是 table 的条件格式,您可能需要考虑 gt 包:

library(gt)

thi %>% gt()

或者这样:

thi %>% gt() %>% 
  data_color(
    columns = vars(thi), 
    colors = scales::col_factor(
      palette = "Set1",
      domain = NULL
    ))

或者这样:

thi %>% gt() %>%
  tab_style(
    style = cells_styles(
      bkgd_color = "#F9E3D6",
      text_style = "italic"),
    locations = cells_data(
      columns = vars(thi),
      rows = thi <= 7
    )
  )