r - 在函数中使用 geoms
问题描述
我想编写一个函数来绘制镜头位置数据。我的函数将 NHL 溜冰场的图像设置为背景,然后调用geom_point
并coord_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()
是什么导致了这个错误,我该如何解决?
解决方案
对我来说,对自定义函数进行故障排除的第一步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()
因为稍后调用该函数时您不希望传递任何参数。
推荐阅读
- android - 如何在单行上保持两个 TextInputLayouts 一致的宽度
- linux - 选择特定路线/路径到目的地地址
- mysql - 使用数据库管理工具从 ubuntu 服务器连接 mysql 的问题
- r - 如何重新排列R中的单个单元格?
- angular - 无法以角度从导航栏组件html调用组件
- c - 实现一个数据结构来保存一个字符流
- php - 如何从 PDO fetchAll() 中删除第一个数组?
- javascript - 平均堆栈:我们可以同时使用 body-parser 和 multer 中间件吗?
- javascript - 标识符“authService”指的是组件的私有成员
- python - IndexError:在python中列出索引超出范围,即使范围存在