0

I'd like to combine a hexbin plot with a ggplot in different panels in R. I can get kinda close, but it's still not working:


library(hexbin)
library(ggplot2)
library(grid)

x1 <- rnorm(100)
y1 <- rnorm(100)

x2 <- rnorm(100, 1, 0.2)
y2 <- rnorm(100, 1, 0.2)


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

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

# ggplot
df <- data.frame(x1=x1, y1=y1)
g <- ggplot(df, aes(x=x1, y=y1)) + geom_point(aes(x=x1, y=y1))

### KINDA WORKS

grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))
pushViewport(viewport(layout.pos.col=1, layout.pos.row=1))
print(g)

pushViewport(viewport(layout.pos.col = 2, layout.pos.row = 1))
plotFrame <- plot(h1, type='n', newpage=FALSE)
pushHexport(plotFrame$plot.vp, clip='on')
grid.hexagons(h1, style='constant.col', border='white', pen='blue')
grid.hexagons(h2, style='constant.col', border='white', pen='red')

I think one of the complications is that, as you can see, I am overlaying two hexbin objects in the same plot. Here's what I get:

enter image description here

I'd like the scatter plot (ggplot) to be in the left and the hexbin plot to be in the right panel, like this (made manually):

enter image description here

I think one of the complications is that, as you can see, I am overlaying two hexbin objects in the same plot.

My understanding is that the hexbin and ggplot2 packages are both using the grid graphics system, which would seem to imply I could use one of several ways to combine the panels (e.g., how to do that with different packages). However, the hexbin package uses pushHexport, which makes any of those solutions unworkable.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Eden
  • 335
  • 2
  • 8
  • it's been a long time, but is there a possibility that you could use `geom_hexbin()` from within `ggplot` for your hexbin? – Ben Bolker Jul 08 '21 at 03:57
  • 1
    Thanks for the suggestion--I actually just did stumble on geom_hexbin(). It seems to work for this issue and is much easier to do compared to wrestling with pushHexport(). – Eden Jul 12 '21 at 21:16

0 Answers0