如何在R中复制带有六边形图的散点图?

时间:2016-03-08 16:03:06

标签: r plot ggplot2

我相信我接近用hexbin plot正确地复制我的散点图。

我当前的散点图:

ggplot(shotchart[shotchart$player_id==X,], aes(as.numeric(V1), as.numeric(V2))) + 
annotation_custom(court, -3, 100, -102, 3) +
geom_point(aes(colour = class, alpha = 0.8), size = 3) +
scale_color_manual(values = c("#008000", "#FF6347")) +
guides(alpha = FALSE, size = FALSE) +
xlim(-1, 102) +
ylim(102, -3) +
coord_fixed()

散点图的样子: enter image description here

我的己基图:

ggplot(shotchart[shotchart$player_id==X,], aes(x=as.numeric(V1), y=as.numeric(V2))) + 
annotation_custom(court, -3, 100, -102, 3) +
geom_hex(aes(alpha= .3, fill = class, bins = 25))+
guides(alpha = FALSE, size = FALSE) +
xlim(-1, 102) +
ylim(102, -3) +
coord_fixed()

hexbin图是什么样的:

![enter image description here

我相信两个情节都在说同样的话。从图中我希望能够看到拍摄“镜头”的位置,以及镜头是“制作”还是“遗漏”散点图完美地描绘了这一点。但对于hexbin,它没有正确显示“make”或“miss”

我已经圈出了hexbin图中的主要问题区域。 深蓝色的区域实际上应该是深红色。散点图中绿色和深绿色的区域在hexbin图中应为红色和深红色。我尝试更改hexbin图中的alpha,但我无法将深蓝色更改为深红色。

任何帮助将不胜感激。我是新手使用ggplot所以如果需要任何进一步的信息,请告诉我。

1 个答案:

答案 0 :(得分:2)

如果没有可重复的例子,我无法确定,但我认为正在发生的事情是红色和蓝色六边形在重叠制作和错过镜头的区域中相互重叠。您在这些区域看到的较暗的颜色是混色的结果。解决方案是为六边形使用较小的箱尺寸。但是,如果在同一位置制作和丢失镜头,您仍然会有一些重叠的六边形。

以下是假数据的示例:

set.seed(494)
dat = data.frame(x = c(runif(1000,0,0.5),runif(100,0.5,1)), y=c(runif(1000,0,0.5),runif(100,0.5,1)), 
                 group=c("Made","Missed"))

ggplot(dat, aes(x,y,colour=group)) +
  geom_point(alpha=0.5)

ggplot(dat, aes(x,y,fill=group)) +
  geom_hex(alpha=0.5, bins=30) + ggtitle("bins=30")

ggplot(dat, aes(x,y,fill=group)) +
  geom_hex(alpha=0.5, bins=80) + ggtitle("bins=80")

下面的前两个图比较绘制点以绘制六边形区域。请注意,左下象限有许多重叠点。结果,存在重叠的六边形。我们可以通过增加箱的数量来减少重叠六边形的数量,如底部图中所做的那样。

enter image description here

enter image description here

您是否有理由更喜欢六角形分档而不是分数? hexbins只计算了球场每个区域的投篮数和投篮数。使容器足够小以最小化重叠基本上使您回到散点图(即,容器大约是点标记的大小)。在这种情况下,您可以使用带有六边形点标记的geom_point。另一方面,你真的想知道球场不同区域投篮的比例吗?像这样的东西,例如:

library(scales)

dat$made.flg = ifelse(dat$group=="Made", 1, 0)

ggplot(dat, aes(x, y, z=made.flg)) +
  stat_summary_hex(fun=mean, bins=30) +
  scale_fill_gradient(low="blue", high="red", labels=percent_format(), name="Pecent Made")

enter image description here