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:
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):
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.