如何在ggplot2中的geom_hex图中对齐六边形

问题描述

我正在尝试将两个数据源组合成一个二维十六进制图,以便它们具有相同的配准(因此数据集 1 中的十六进制与数据集 1 中的十六进制对齐)和绘制时正确的十六进制大小.唉,到目前为止失败了:

library(hexbin)
library(ggplot2)

set.seed(123)
x1 <- rnorm(10000)
y1 <- rnorm(10000)

x2 <- rnorm(100,2)
y2 <- rnorm(100)

xbnds <- range(c(x1,x2))
ybnds <- range(c(y1,y2))
xbins <- 20

h1 <- hexbin(x1,y1,xbnds=xbnds,ybnds=ybnds,xbins=xbins)
h2 <- hexbin(x2,y2,xbins=xbins)

df1 <- data.frame(hexbin::hcell2xy(h1),cell=h1@cell,count=h1@count)
df2 <- data.frame(hexbin::hcell2xy(h2),cell=h2@cell,count=h2@count)
df1$type <- 'a'
df2$type <- 'b'

df <- rbind(df1,df2)
df$type <- as.factor(df$type)

p <- ggplot(data=df,aes(x=x,y=y)) +
    geom_hex(data=df,y=y,fill=stat(density),color=factor(type)),alpha=0.5)
    
p

mis-aligned hex bins

我原以为指定 x 和 y 边界以及 x 维度中的六边形数量会使六边形对齐。

也许是一个相关的问题——六角形似乎太小了,或者至少没有覆盖样本空间。 Perforce,这是使用 hexbin 包 (plot(h1)) 的图:

hexbin hexes

一个图中的“type a”十六进制应该是这样的,但不是!此图的宽度为 20 个十六进制,但 ggplot2 版本的宽度更多。

提前致谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)