Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make stat_binhex shown on a log scale in ggplot2

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()
like image 492
user3389288 Avatar asked Oct 15 '14 03:10

user3389288


2 Answers

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

like image 82
Taekyun Kim Avatar answered Oct 18 '22 09:10

Taekyun Kim


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

like image 35
Artem Fedosov Avatar answered Oct 18 '22 10:10

Artem Fedosov