wilkelab / ggtext

Improved text rendering support for ggplot2
https://wilkelab.org/ggtext/
GNU General Public License v2.0
655 stars 37 forks source link

Overlay data table in plot #36

Open paco-ceam opened 4 years ago

paco-ceam commented 4 years ago

Hi everyone

I'm plotting a weekly temperature data series (values every 10 minutes) and would like to overlay a table with daily max/min temperature in my plot. Max/min temp are in a dedicated data.frame object. Is it possible to use geom_richtext in this case?

Thanks in advance

higgi13425 commented 4 years ago

Could use paste to make a new var that combines date, min, max and a line break
, then collapse(dataframe$new_var) to a single text string, then use geom_richtext. This ends up with one blank line at the end, but you could use str_extract and regex to remove the last
. I think that this is a fairly common use case for small tables, and might be worth a function

higgi13425 commented 4 years ago

Example (can likely be done much more elegantly)

  1. make table iris %>% count(Species) %>% select(n, Species) -> table
  2. make combined text var table <- table %>% mutate(text_var = paste(as.character(n), as.character(Species), "<br>"))
  3. glue_collapse text_var text <- glue_collapse(table$text_var)
  4. strip off final line break text <- str_extract(text, pattern = "^.+(?= <)")
  5. now use geom_richtext(label = text) and get your table
r2evans commented 1 year ago

I know it's been a while, but one option is to use gridExtra::tableGrob and patchwork (and, for now at least, not ggtext):

library(ggplot2)
library(dplyr)
library(patchwork)
counts <- count(mtcars, cyl)
counts
#   cyl  n
# 1   4 11
# 2   6  7
# 3   8 14
tab <- gridExtra::tableGrob(counts, rows = rep("", nrow(counts)))
gg <- ggplot(mtcars, aes(mpg, disp)) + geom_point()

With that setup, we can do

gg + inset_element(tab, left = 0.7, bottom = 0.7, right = 1, top = 1)

image

gg + tab + plot_layout(widths = c(4, 1))

image

There are many theming options for the table, such as font, color (fg_params), fill (bg_params), etc. See its vignette, https://cran.r-project.org/web/packages/gridExtra/vignettes/tableGrob.html for a good start.

(This is applicable to https://github.com/wilkelab/ggtext/issues/39 as well.)