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

Programmatic way to include grobs #24

Open
teunbrand opened this issue Jun 1, 2024 · 2 comments
Open

Programmatic way to include grobs #24

teunbrand opened this issue Jun 1, 2024 · 2 comments

Comments

@teunbrand
Copy link
Contributor

Hi Thomas,

This continues a few comments that we exhanged off-github; I'm having difficulty providing an element_marquee() with a programatically generated list of grobs.

From the code below, I'd like to render the pts$foo grob in the text.

library(marquee)
library(ggplot2)
library(grid)

# Populate element
el  <- ggplot2:::combine_elements(element_marquee(), theme_get()$text)

txt <- "Here be ![](foo) a point"
pts <- list(foo = pointsGrob(0.5, 0.5, default.units = "npc"))
expr <- rlang::expr(element_grob(el, label = txt))

For clear reasons, this wouldn't work out of the box, as the desired grob is in a list somewhere, not the current environment.

grob <- rlang::eval_tidy(expr)
grid.newpage()
grid.draw(grob)

Your suggestion at the time, to use a data mask does not work as I had hoped.

grob <- rlang::eval_tidy(expr, data = pts)
grid.newpage()
grid.draw(grob)

Neither does providing the grobs as the env argument.

grob <- rlang::eval_tidy(expr, env = list2env(pts))
grid.newpage()
grid.draw(grob)

After some trial and error, what I found that did work was to use a local environment. This is fine for my purposes, but I'd prefer it if there were an easier way to do this.

grob <- withr::with_environment(list2env(pts), rlang::eval_tidy(expr))
grid.newpage()
grid.draw(grob)

Created on 2024-06-01 with reprex v2.1.0

@lionel-
Copy link
Member

lionel- commented Jun 3, 2024

I wonder if we should advise evalq(myexpr(), pts). Does this work as expected too?

@thomasp85
Copy link
Member

grob <- evalq(element_grob(el, label = txt), pts)
grid.newpage()
grid.draw(grob)

also fails to find the object

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