gpt4 book ai didi

r - 在函数中使用几何

转载 作者:行者123 更新时间:2023-12-05 03:58:21 26 4
gpt4 key购买 nike

我想编写一个函数来绘制镜头位置数据。我的函数将 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()

enter image description here

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

最佳答案

对我来说,对 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 对象是列表,列表中的每个元素都包含您使用 + 指定的层。我无法完全解释的是为什么在某些情况下使用 + 构建函数不起作用。但是我在创建图层的 list() 时没有遇到任何问题。

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

关于r - 在函数中使用几何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58072649/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com