9

I have a 2d hexagon density plot with many points. I would like the counts within the hexagons to be displayed on a logarithmic scale, but I can't figure out how to do this through ggplot2.

Here is a simple example:

x <- runif(1000, 50, 100) 
y <- rnorm(1000, mean = 10, sd = 8)

df <- as.data.frame(cbind(x, y))

ggplot(df, aes(x, y)) + stat_binhex()
user3389288
  • 992
  • 9
  • 30

2 Answers2

12

Another way is to pass trans = argument to scale_fill_* used.

ggplot(df, aes(x, y)) + geom_hex() + scale_fill_gradient(trans = "log")
ggplot(df, aes(x, y)) + geom_hex() + scale_fill_viridis_c(trans = "log")

enter image description here

Taekyun Kim
  • 146
  • 1
  • 3
10

There is a fill aesthetics that defaults to ..count.. when you do not specify it in stat_binhex. The code below produces same plot as your original code.

ggplot(df, aes(x, y)) + stat_binhex(aes(fill=..count..))

enter image description here

If you want to have a log scale for counts, then the solution is pretty straight forward:

ggplot(df, aes(x, y)) + stat_binhex(aes(fill=log(..count..)))

enter image description here

Artem Fedosov
  • 2,163
  • 2
  • 18
  • 28
  • 2
    This doesn't work for me in ggplot2_2.1.0: Error in eval(expr, envir, enclos) : object 'count' not found – daknowles Mar 30 '16 at 05:32
  • 1
    @daknowles this is most likely caused by a bug in ggplot2: [#1608](https://github.com/hadley/ggplot2/issues/1608) – FloE Jul 19 '16 at 14:39
  • As of ggplot 3.4.0 one should use `after_stat(count)` instead of `..count..` as the latter is deprecated – nebroth Jun 16 '23 at 14:04