首页 > 解决方案 > 在函数中使用 geoms

问题描述

我想编写一个函数来绘制镜头位置数据。我的函数将 NHL 溜冰场的图像设置为背景,然后调用geom_pointcoord_flip正确映射位置数据。

geom_shotplot <- function(...){
  annotation_custom(grid::rasterGrob(png::readPNG("man/figures/full-rink.png"), 
                               width = unit(1,"npc"), 
                               height = unit(1,"npc"))) +
    geom_point() +
    coord_flip()
}

但是,该函数返回错误:

x_coords <- rnorm(100)
y_coords <- rnorm(100)

my_data <- data.frame(x_coords=rnorm(100, sd=10),y_coords=rnorm(100, sd=10))

ggplot(my_data, aes(x=x_coords, y=y_coords)) +
   geom_shotplot()

错误:无法将 ggproto 对象添加在一起。您是否忘记将此对象添加到 ggplot 对象?

当我在函数之外使用相同的代码时,它可以完美运行:

ggplot(my_data, aes(x=x_coords, y=y_coords)) +
annotation_custom(grid::rasterGrob(png::readPNG("man/figures/full-rink.png"), 
                               width = unit(1,"npc"), 
                               height = unit(1,"npc"))) +
    geom_point() +
    coord_flip()

在此处输入图像描述

是什么导致了这个错误,我该如何解决?

标签: rggplot2

解决方案


对我来说,对自定义函数进行故障排除的第一步ggplot2是首先尝试将图层设置为列表。因此,如果您的自定义功能在这里不起作用,您可以求助于:

geom_shotplot <- function() {
      list(
   annotation_custom(grid::rasterGrob(png::readPNG("man/figures/full-rink.png"), 
                               width = unit(1,"npc"), 
                               height = unit(1,"npc"))),
    geom_point(),
    coord_flip()
     )
}

要记住的关键方面是ggplot2对象是列表,列表的每个元素都由您使用指定的层组成+。我无法完全解释的是为什么在某些情况下使用 inside 构建函数+不起作用。list()但是我在创建图层时没有任何问题。

请注意,您不需要...in,function()因为稍后调用该函数时您不希望传递任何参数。


推荐阅读