3

I have a function (col_grob) that calls another function (pal_bar) with a tilde-notation expression as follows:

## plots a colour bar with specified colour intervals
pal_bar <- function(cols) {
  cols <- colorRampPalette(cols)(200)
  par(mar = c(0, 0, 0, 0))
  plot(1:200, rep(1, 200), col = cols, pch = 15, cex = 1.1, bty = 'n', xaxt = 'n', xlab = '', yaxt = 'n', ylab = '', main="")
}

## calls pal_bar function to plot the bar as a grob, tilde expression
col_grob <- function(pal) {
  g <- ggplotify::as.grob(~pal_bar(pal))
  grid::grid.draw(g)
}

I am returned the error "object 'pal' not found" when I run:

col_grob(pal = c("red", "blue"))

I came across resources and similar questions but I am not able to solve the issue with my lack of understanding of the evaluation rules. I tried ~pal_bar(I(pal)), bquote() function, and possibly structure(list(), *) but do not have sufficient knowledge of each to format the syntax correctly.

How would I get col_grob(pal = c("red", "blue")) to plot the desired colour bar for me? enter image description here

Jane
  • 517
  • 4
  • 15

1 Answers1

2

A possible solution:

col_grob <- function(pal) {
  txt <- substitute(pal_bar(pal))
  g <- ggplotify::as.grob(as.expression(txt))
  grid::grid.draw(g)
}

col_grob(pal = c("red", "blue"))
Marco Sandri
  • 21,986
  • 7
  • 43
  • 51