2

Trying to improve this code. What I have worked up works but looks ugly and is VERY clumsy.

Looking for a ggplot method or something that is more user friendly. Would appreciate the tips and advice.

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)
EDennnis
  • 191
  • 1
  • 11

1 Answers1

6

How about this:

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

Or depending on whether thi is really factor (discrete) or continuous variable, you may want something like this:

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

Option 2

Note: You probably want to avoid using column or variable names that are reserved words or abbreviations (e.g. avoid calling something T because that's an abbreviation for the keyword TRUE). In the code above, I renamed the columns of your data.frame.


Since the question says conditional formatting of a table, however, you may want to consider the gt package:

library(gt)

thi %>% gt()

GT Table One

Or this:

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

GT Table 2

Or maybe this:

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

JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116
  • Thank you @JasonAizkalns. Soooo much better than my clumsy code. Appreciate the insight. – EDennnis Mar 09 '19 at 19:01
  • 1
    how would I put a threshold value in this? For example if I want all the values >= 10 to be red, <=5 to be blue, and 5< x <10 to be yellow. Does this enter through another variable in the ggplot2 command. Been looking and cannot find this anywhere. Thanks – EDennnis Jun 17 '19 at 14:26