Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine multiple ggplot2 elements into the return of a function?

Tags:

If I try to manually compose some elements of a ggplot2 plot, it works just fine:

> p <- ggplot(aes(x = mpg, y = hp), data = mtcars) > p + geom_vline(xintercept = 20) + geom_point(data = mtcars) 

But if I try to bundle some of the composition into a function, I get an error:

> myFunction <- function() { +   return( +     geom_vline(xintercept = 20) + geom_point(data = mtcars) +   ) + } > p <- ggplot(aes(x = mpg, y = hp), data = mtcars) > p + myFunction() Error in geom_vline(xintercept = 20) + geom_point(data = mtcars) :    non-numeric argument to binary operator 

Am I missing something in ggplot2 notation for properly combining ggplot2 elements within a function body?

like image 424
briandk Avatar asked Jan 29 '11 05:01

briandk


People also ask

Which ggplot2 connects multiple operations?

Integrating the pipe operator with ggplot2 We can also use the pipe operator to pass the data argument to the ggplot() function. The hard part is to remember that to build your ggplot, you need to use + and not %>% . The pipe operator can also be used to link data manipulation with consequent data visualization.


1 Answers

ggplot2 supports "list" of the elements:

myFunction <- function()  list(geom_vline(xintercept = 20),       geom_point(data = mtcars))  p <- ggplot(aes(x = mpg, y = hp), data = mtcars) p + myFunction() 

you can keep in a list any piece that ggplot2 function returns, including labs(), opts(), etc, and then use "+" for bind ggplot2 base layer and the piece in the list.

Probably this feature is not widely known , but is very useful when anyone want to re-use a piece of elements.

like image 81
kohske Avatar answered Sep 21 '22 14:09

kohske