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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With