johannes
johannes

Reputation: 14453

`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

Upvotes: 0

Views: 67

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269852

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")) ##

Upvotes: 1

Related Questions