【问题标题】:Conditional formatting of table in R...a better way?R中表格的条件格式...更好的方法?
【发布时间】:2019-03-08 15:54:14
【问题描述】:

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

正在寻找 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】:

    这个怎么样:

    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 的列。


    由于问题是表格的条件格式,但是,您可能需要考虑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
        )
      )
    

    【讨论】:

    • 谢谢@JasonAizkalns。 Soooo 比我笨拙的代码好多了。欣赏洞察力。
    • 如何在其中设置阈值?例如,如果我希望所有值 >= 10 为红色,
    猜你喜欢
    • 2015-06-24
    • 2014-11-28
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    相关资源
    最近更新 更多