ggplot:基于两个不同的图形组合,创建一个新的图形。

3

我有两个图层,例如geom_smoothgeom_point。我想创建一个新的独立图层geom_smoothpoint,它将绘制这两个图层。

我希望实现以下效果:

ggplot(iris, aes(x=Sepal.Length, y=Petal.Width)) +
  geom_smoothpoint()

以与下面相同的结果:

ggplot(iris, aes(x=Sepal.Length, y=Petal.Width)) +
  geom_point() +
  geom_smooth(method="lm")

在此输入图片描述

我尝试将这两个东西结合起来:


(注:该文本为HTML代码,如需查看翻译效果请在HTML环境下查看)
geom_smoothpoint <- function(){
  geom_point() +
  geom_smooth(method="lm")
}

但它并不真正起作用。看来我必须组合ggproto对象,但我不确定该如何操作。有没有将两个几何图形组合成一个的简单方法?谢谢!

1个回答

4

当然你可以自己编写geom,但这是过度设计。更简单的方法是在函数中返回一个列表,并将其方便地添加到您的图表中:

geom_smoothpoint <- function() {
   list(geom_point(), geom_smooth(method = "lm"))
}

ggplot(iris, aes(x=Sepal.Length, y=Petal.Width)) +
   geom_smoothpoint()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接