1

I'm trying to combine two sources of data into one 2-dimensional hex plots so that they have the same registration (so the hexes from data set 1 align with the hexes from data set 1) and proper hex size when plotted. Alas, failure so far:

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, xbnds=xbnds, ybnds=ybnds, 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, aes(x=x, y=y, fill=stat(density), color=factor(type)), alpha=0.5)
    
p

mis-aligned hex bins

I had thought that specifying the x- and y-bounds and the number of hexes in the x-dimension would align the hexes.

Maybe a related problem--the hexes seem to be too small, or at least don't cover the sample space. Perforce, here's the plot using the hexbin package (plot(h1)):

hexbin hexes

The "type a" hexes in the first figure should look like this, but no! This plot has a width of 20 hexes, but the ggplot2 version has more.

Thanks in advance!

Axeman
  • 32,068
  • 8
  • 81
  • 94
Eden
  • 335
  • 2
  • 8

0 Answers0