Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ggplot, how can I get two legends ("gradient" type) for stat_bin2d?

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.

enter image description here

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')))
like image 237
Alessandro Jacopson Avatar asked Dec 02 '25 07:12

Alessandro Jacopson


2 Answers

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()

different colours

like image 137
Z.Lin Avatar answered Dec 04 '25 20:12

Z.Lin


Using alpha = ..density.. does the trick:

ggplot(df, aes(x = x, y = y) ) + 
  stat_bin2d(mapping= aes(alpha = ..density.., fill = type)) 

enter image description here

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) 

enter image description here

like image 20
Edgar Santos Avatar answered Dec 04 '25 21:12

Edgar Santos