问题
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')))
回答1:
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()
回答2:
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)
来源:https://stackoverflow.com/questions/46276771/in-ggplot-how-can-i-get-two-legends-gradient-type-for-stat-bin2d