这个怎么样:
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 (离散)或连续变量,你可能想要这样的东西:
thi
factor
ggplot(thi, aes(x = col1, y = col2, fill = thi, label = thi)) + geom_tile() + geom_text(color = 'white')
注意:您可能希望避免使用保留字或缩写的列或变量名(例如,避免调用某些内容 T 因为那是关键字的缩写 TRUE )。在上面的代码中,我重命名了data.frame的列。
T
TRUE
既然问题是表格的条件格式,你可能想要考虑 gt 包:
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 ) )