user1707322
user1707322

Reputation: 87

passing geoms to function

I am interested in combining geoms for plots so I can reuse combinations of geoms. Take for example the following function

draw_curve = function(from = -pi, to = pi, fun = sin, plotfun = geom_line, length.out = 100, ...) { 
  x = seq(from, to, (to-from)/length.out)
  y = fun(x)
  sindf = data.frame(x = x, y = y)
  ggplot(sindf, aes(x = x, y = y)) + 
    plotfun(...)
}

Now the following works:

draw_curve(plotfun = geom_point)

and even the following:

draw_curve(plotfun = function(...) geom_line(size = 3, color = 'red', ...))

However, the following does not:

draw_curve(plotfun = function(...) geom_line(size = 3, color = 'red') + geom_point(shape=21))

I can understand why it doesn't work because '+' is an overloaded operator that apparently expects a plot object on the left hand side and a geom on the right hand side. Also the result of plot+geom is a plot and '+' is evaluated from left to right so that is why ggplot works with the syntax for adding geoms.

Now my question is what is the easiest why to create a composite geom that I can easily pass into a function.

Upvotes: 1

Views: 100

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270348

Put the geoms in a list:

linepoint <- function(...) list(geom_line(size = 3, color = 'red'), geom_point(shape=21))
draw_curve(plotfun = linepoint)

Upvotes: 3

Related Questions