我对组合图形的地块感兴趣,因此我可以重复使用组合的图形。以下面的函数为例
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(...)
}
现在可以进行以下工作:
draw_curve(plotfun = geom_point)
甚至以下内容:
draw_curve(plotfun = function(...) geom_line(size = 3, color = 'red', ...))
但是,以下内容却没有:
draw_curve(plotfun = function(...) geom_line(size = 3, color = 'red') + geom_point(shape=21))
我可以理解为什么它不起作用,因为“ +”是一个重载运算符,显然希望左侧有一个图对象,而右侧有一个geom。而且plot + geom的结果是一个图,并且从左到右计算'+',这就是为什么ggplot可以使用添加geoms的语法的原因。
现在我的问题是为什么创建一个可以轻松传递给函数的复合几何图形最简单?
答案 0 :(得分:2)
将几何图形放入列表中
linepoint <- function(...) list(geom_line(size = 3, color = 'red'), geom_point(shape=21))
draw_curve(plotfun = linepoint)