Skip to content

Instantly share code, notes, and snippets.

@wahalulu
Created November 18, 2011 16:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wahalulu/1376861 to your computer and use it in GitHub Desktop.
Save wahalulu/1376861 to your computer and use it in GitHub Desktop.
Use ggplot to make a hexbin plot using hexbin for binning
library(hexbin)
library(ggplot2)
library(Hmisc)
## The following function cretes a hexbinplot from a dataset using ggplot
## for graphing but hexbin for doing the hexbinning.
## xvar and yvar are the x and y data
## bins is the number of bins to pass into the hexbin function
## cuts is the number of steps to use in a discrete color scale
make.hexbin.ggplot <- function(xvar, yvar, bins, cuts) {
hex <- hexbin(xvar, yvar, bins)
gghex <- data.frame(hcell2xy(hex), count = hex@count,
xo = hex@xcm, yo = hex@ycm,
c = cut2(hex@count, g = cuts))
plot <- ggplot(gghex) +
geom_hex(aes(x = x, y = y, fill = c),
color = "black", stat = "identity")
list(gghex = gghex, hexplot = plot)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment