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

旧巷老猫 提交于 2019-12-23 19:27:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!