如何将多个 ggplot2 元素组合到函数的返回中?
如果我尝试手动组合 ggplot2 绘图的某些元素,它工作得很好:
> p <- ggplot(aes(x = mpg, y = hp), data = mtcars)
> p + geom_vline(xintercept = 20) + geom_point(data = mtcars)
但是如果我尝试将一些组合捆绑到函数中,则会收到错误:
> 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
我在 < 中遗漏了某些内容吗?用于在函数体内正确组合 ggplot2 元素的 code>ggplot2 表示法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ggplot2 支持元素的“列表”:
您可以将 ggplot2 函数返回的任何部分保留在列表中,包括 labs()、opts() 等,然后使用“+”绑定 ggplot2 基础层和列表中的部分。
可能这个功能并不广为人知,但是当任何人想要重复使用某个元素时非常有用。
ggplot2 supports "list" of the elements:
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.