Search code examples
rconditional-statementsgridextragrob

Ho to highlight conditional values in a two way table graphing with TableGrob in R?


I would like to graph a table in R where I highlight a value with a condition of 'less than 2' in Red, for example. Any help on how I can do this?

data(iris)
iris <- iris[1:4, 1:3]
rownames(iris) <- as.character(as.yearmon(
  seq(as.Date("2020/1/1"), as.Date("2020/4/1"), by = "month")))
colnames(iris) <- as.character(as.yearmon(
  seq(as.Date("2020/5/1"), as.Date("2020/8/1"), by = "month")))
iris

tg <- tableGrob(iris)
grid.draw(tg)

Solution

  • You can use gridExtra and condformat to make it easier:

    library(gridExtra)
    library(condformat)
    
    t <- condformat(iris) %>%
         rule_text_color(Sepal.Length, ifelse(Sepal.Length >= 4.6, "red", "")) %>%
         condformat2grob()
    
    p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + 
         geom_point()
    
    grid.arrange(p ,t, nrow=1)
    

    enter image description here