0

I made a bar plot with ggplot2 that contains a data table within its plot area. How can I colorize text elements within this data table?

I know how to colorize text with "geom_richtext", but how is it done in a data table ?

The example below draws the bar plot, a data table within the area, and text (where colors can be applied). But how can they be applied to table elements (e.g. to the words within table cells)?

library(ggplot2)
library(ggtext)
library(ggpmisc)
library(ggpp)

data = data.frame(
  colors = c('black, red, black again', 'green, yello, now blue'), 
  x = c(1, 2),
  y = c(5, 10))

gg = ggplot(data, aes(x = x, y = y)) +
     geom_bar(stat = 'identity', fill = 'blue')

gg = gg +
     annotate(geom = 'table', x = 1, y = 7, label = list(data), parse = F) 

mytext = glue::glue("black, <span style = \'color: red;\'>red</span>, black again ....")

gg = gg +
     geom_richtext(aes(x = 1.5, y = 3, label = mytext), label.color = NA)

gg
Captain Hat
  • 2,444
  • 1
  • 14
  • 31
  • 1
    `geom_table` does not use rich text. Its drawing method uses `gridExtra::tableGrob`, which _could_ use rich text with a lot of cajoling, but `geom_table` is hard coded to use a text grob rather than a rich text grob. If this is very important to you, then the solution is to build the table yourself out of `geom_tile` or `geom_rect` layers and add the text via `geom_richtext`. (It would also be possible, but even more convoluted, to add a tableGrob that uses richtext as a custom annotation. This seems like too much work for the end result) – Allan Cameron Nov 21 '22 at 15:17
  • 1
    Is it really necessary to use ggplot for that? In the alike case I shifted to `flextable` allowing you to set backgrounds and of other rich text attributes with rendering of this output afterwards. – asd-tm Nov 21 '22 at 15:44
  • ....flextable .. that's an interesting thought ... did you combine it with a plot? – ulrichstefenelli Nov 22 '22 at 14:09

0 Answers0