R中表格的条件格式化...更好的方法?

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

试图改进这段代码。我的工作起作用,但看起来很丑,非常笨拙。

寻找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)
r ggplot2 conditional-formatting
1个回答
4
投票

这个怎么样:

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()

Option 1

或者取决于thi是否真的是factor(离散)或连续变量,你可能需要这样的东西:

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

Option 2

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


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

library(gt)

thi %>% gt()

GT Table One

或这个:

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

GT Table 2

或许这个:

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

GT Table 3

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