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

时间:2019-03-08 15:54:14

标签: r ggplot2 conditional-formatting

尝试改进此代码。我所做的工作正常,但看起来很丑,非常笨拙。

寻找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)

1 个答案:

答案 0 :(得分: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