Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Overlay data table in plot #36

Open
paco-ceam opened this issue May 27, 2020 · 3 comments
Open

Overlay data table in plot #36

paco-ceam opened this issue May 27, 2020 · 3 comments

Comments

@paco-ceam
Copy link

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
Copy link

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
Copy link

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
Copy link

r2evans commented Jun 29, 2023

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 #39 as well.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants