3

我的目标是结合使用 ggplot2 和 ggforce 包来绘制 NBA 篮球场的尺寸/线条。我已经使用 + geom_segment() 图层成功绘制了线段(边线、罚球线等),但我很难使用 + geom_circle() 和 + geom_arc() 函数来绘制圆圈和圆弧(三点线、半场圆等)

我的代码如下,其中对象“样本”只是一个镜头数据框,具有 x 和 y 坐标:

ggplot(sample, aes(shot_x, shot_y)) +
geom_point(color = "red", alpha = .2) +
geom_segment(aes(x = 0, xend = 94, y = 0, yend = 0)) +
geom_segment(aes(x = 0, xend = 94, y = 50, yend = 50)) +
geom_segment(aes(x = 0, xend = 0, y = 0, yend = 50)) +
geom_segment(aes(x = 94, xend = 94, y = 50, yend = 0)) +
geom_segment(aes(x = 0, xend = 14, y = 3, yend = 3)) +
geom_segment(aes(x = 80, xend = 94, y = 3, yend = 3)) +
geom_segment(aes(x = 0, xend = 14, y = 47, yend = 47)) +
geom_segment(aes(x = 80, xend = 94, y = 47, yend = 47)) +
geom_segment(aes(x = 47, xend = 47, y = 0, yend = 50)) +
geom_segment(aes(x = 0, xend = 19, y = 19, yend = 19)) +
geom_segment(aes(x = 0, xend = 19, y = 31, yend = 31)) +
geom_segment(aes(x = 75, xend = 94, y = 19, yend = 19)) +
geom_segment(aes(x = 75, xend = 94, y = 31, yend = 31)) +
geom_segment(aes(x = 19, xend = 19, y = 19, yend = 31)) +
geom_segment(aes(x = 75, xend = 75, y = 19, yend = 31)) +
geom_segment(aes(x = 4, xend = 4, y = 22, yend = 28)) +
geom_segment(aes(x = 90, xend = 90, y = 22, yend = 28)) +
coord_fixed(ratio = 1)

当我添加:

+ geom_circle(aes(x0 = 47, y0 = 25, r = 6))

(应该在半场画一个圆圈),可视化上没有圆圈,结果包括初始图形(线段和投篮点),以及所有数据点的副本,但向上偏移并到正确的。需要明确的是,没有发生错误,只是结果不是我想要的。

此外,当我完全删除 geom_point() 层时,并启动如下代码:

ggplot() +
geom_segment(...)

然后我可以成功添加 geom_circle() 图层。但是,我需要能够添加圆圈并包含数据点。

知道为什么会这样,或者我做错了什么吗?谢谢!

4

1 回答 1

6

不知道为什么,但inherit.aes = FALSEgeom_circle调用中添加可以修复它。

library(ggforce) # geom_circle used to be in ggplot2, now is in ggforce
sample = data.frame(shot_x = c(10, 20), shot_y = c(30, 40))
ggplot(sample, aes(shot_x, shot_y)) +
  # ... all your segment lines
  coord_fixed(ratio = 1) +
  geom_circle(aes(x0 = 47, y0 = 25, r = 6), inherit.aes = FALSE)

输出

于 2018-08-27T20:42:54.687 回答