Henk Henk - 2 months ago 22
R Question

geom_hexbin map bincount to alpha

I would like the geom_hex bincount to alpha, as done here.

Somehow it doesn't work for me, what could be wrong? (dev version of ggplot2?) :

library(ggplot2)
library(reshape2)

dm <- melt(diamonds, measure.var = c('depth','carat'))

ggplot(dm, aes(y = price, fill = variable, x = value)) +
facet_wrap(~variable, ncol = 1, scales = 'free_x') +
stat_binhex(aes(alpha = ..count..), colour = 'grey80') +
scale_alpha(name = 'Frequency', range = c(0,1)) +
theme_bw() +
scale_fill_manual('Variable', values = setNames(c('darkblue','yellow4'), c('depth','carat')))

Error in eval(expr, envir, enclos) : object 'count' not found


sessionInfo:

R version 3.2.3 (2015-12-10)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.1 LTS

locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C LC_TIME=nl_NL.UTF-8 LC_COLLATE=en_US.UTF-8 LC_MONETARY=nl_NL.UTF-8 LC_MESSAGES=en_US.UTF-8 LC_PAPER=nl_NL.UTF-8
[8] LC_NAME=C LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=nl_NL.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] hexbin_1.27.1 reshape2_1.4.1 ggplot2_2.1.0.9000

loaded via a namespace (and not attached):
[1] Rcpp_0.12.7 lattice_0.20-33 assertthat_0.1 grid_3.2.3 plyr_1.8.4 gtable_0.2.0 magrittr_1.5 scales_0.4.0 stringi_1.1.1 tools_3.2.3 stringr_1.1.0 munsell_0.4.3
[13] rsconnect_0.4.3 colorspace_1.2-6 tibble_1.2

Answer

There have been changes in the package since then that have altered how ..count.. and ..density.. work with hexbin. The link of @RichardTelford points to a resolved github issue for the ..density.., but ..count.. functionality has not been restored. However, we can simply use ..value.. instead.

ggplot(dm, aes(y = price, fill = variable, x = value)) + 
  facet_wrap(~variable, ncol = 1, scales  = 'free_x') + 
  stat_binhex(aes(alpha = ..value..), colour = 'grey80') + 
  scale_alpha(name = 'Frequency', range = c(0,1)) + 
  theme_bw() + 
  scale_fill_manual('Variable', values = setNames(c('darkblue','yellow4'), c('depth','carat')))

I have reported this as an issue on github.

enter image description here