Here I have two 'clusters', and just one legend.
How can I get two "density" legends with two different color gradients?
I have tried group but it does not work.

The following code generated the above graph:
library(ggplot2)
df <- data.frame(x=c(rnorm(1000,1,.1),rnorm(1000,3,.1)),
y=c(rnorm(1000,1,1),rnorm(1000,3,1)),
type=c(rep('a',1000),rep('b',1000)))
plot( ggplot(df) +
stat_bin2d(aes(x,y,fill=..density..,group='type')))
I'm not aware of a way to specify more than one fill gradient. But here's a work around that uses different transparency levels to simulate the gradient, leaving fill available to be mapped with type:
ggplot(df, aes(x, y, fill = type)) +
stat_bin2d(aes(alpha = ..density..)) +
scale_alpha(range = c(1, 0.1)) +
theme_bw()

Using alpha = ..density.. does the trick:
ggplot(df, aes(x = x, y = y) ) +
stat_bin2d(mapping= aes(alpha = ..density.., fill = type))

A bit more aesthetically using stat_density2d e.g.:
ggplot(df, aes(x=x, y=y) ) +
stat_density2d(mapping= aes(alpha = ..level.., color= type), geom="contour", bins=6, size= 2)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With