rggplot2flextableggpmisc

Highlight max values in annotated table of ggplot


I want to highlight the max values for each column of a annotated table of a ggplot. The best result would be if the result is one ggplot, that I can use in the rest of the code.

with the annotate(…) method of the ggpmisc package, i can create a plot with the added table

library(ggplot2)
library(ggpmisc)
gg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species) ) + 
  geom_point() +
  annotate(geom = "table", 
           x = Inf, y = 0, 
           label = list(head(iris,5 )),
           size=2)
gg1

ggplot with annotated table

I found this answer, which i modified to highlight max values of column instead of rows: https://stackoverflow.com/a/72430256

library(ggplot2)
library(flextable)
library(magrittr)
iris %>% 
  flextable::flextable() -> iris_max_highlight
for(i in seq_len(ncol(iris)))
{
  iris_max_highlight %<>% flextable::bold(which.max(iris[,i]), i)
}
iris_max_highlight

I then tried to somehow combine the result with this answer, to add the modified table to the plot, but couldn't get it to work: https://stackoverflow.com/a/60350244


Solution

  • A more recent option would be to use flextable::gen_grob to convert your flextable to a grob and add it to your plot using patchwork::inset_element:

    library(ggplot2)
    library(patchwork)
    library(flextable)
    library(magrittr)
    
    gg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) +
      geom_point()
    
    ft <- flextable(head(iris))
    
    for (i in seq_len(ncol(iris))) {
      ft %<>% flextable::bold(which.max(head(iris)[, i]), i)
    }
    ft <- ft |>
      fontsize(part = "all", size = 12)
    
    gg1 +
      inset_element(
        gen_grob(ft, fit = "auto"),
        left = 0.4, bottom = 0.01,
        right = .99, top = .4
      )