Search code examples
rggplot2grid

`gggrid` additional arguments in function


gggrid allows to modify a ggplot2 plot directly with grid objects (grobs). The function grid_panel() accepts as first argument either a grob or function. I am looking for way to pass additional argumentes to this function (beside the data and coords).

It seems to work, as long as I stick with the default argument, but as soon as I set this argument, I get an error.

library(ggplot2)
library(gggrid)
data("mtcars")

lab1 <- function(data, coords, label = "ABC") {
  textGrob(label)
}

# This works fine
ggplot(mtcars, aes(x=disp, y=mpg)) +
  geom_point() +
  grid_panel(lab1)

# This does not work
ggplot(mtcars, aes(x=disp, y=mpg)) +
  geom_point() +
  grid_panel(lab1(label = "BCD"))
# Error in lab1(label = "BCD") : 
#  argument "data" is missing, with no default

Solution

  • Use partial from purrr. Only the lines ending in ## have been added/modified.

    library(gggrid)
    library(ggplot2)
    library(purrr) ##
    
    lab1 <- function(data, coords, label = "ABC") {
      textGrob(label)
    }
    
    ggplot(mtcars, aes(x=disp, y=mpg)) +
      geom_point() +
      grid_panel(partial(lab1, label = "BCD")) ##
    

    or without any additional packages

    library(gggrid)
    library(ggplot2)
    
    lab1 <- function(data, coords, label = "ABC") {
      textGrob(label)
    }
    
    ggplot(mtcars, aes(x=disp, y=mpg)) +
      geom_point() +
      grid_panel(function(...) lab1(..., label = "BCD")) ##