Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unusual legend using size mapping and density2d

Tags:

r

ggplot2

I am trying to make a scatterplot in ggplot2 with a size mapping to a third variable and density2d contours. It seems as if the legend is being confused by the inclusion of density2d contours.

For example, the following code works:

library('ggplot2')
set.seed(1)
x=rnorm(100); y=rnorm(100,sd=10); z=seq(1,10,length.out=100)
dd=data.frame(x=x,y=y,z=z)
ggplot(dd,aes(x,y,size=z))+geom_point()

plot looks normal

But now, note the legend behaves unusually when I add in a call to stat_density2d(). In particular, the plot legend shows blue blocks instead of black circles:

ggplot(dd,aes(x,y,size=z))+geom_point()+stat_density2d()

plot legend shows blue blocks instead of black circles

like image 495
JS1204 Avatar asked Apr 17 '13 17:04

JS1204


1 Answers

As size= is one of the aesthetics you can set for the stat_density2d() and in this case it is set in ggplot() call, legend is made for both - lines and points (points are hided under lines in legend as geom_point() is called before stat_density2d()). To remove blue lines from legend, you can set manually size=0.5 (or some other value) inside the stat_density2d() and then legend will be correct.

ggplot(dd,aes(x,y,size=z))+geom_point()+stat_density2d(size=0.5)

enter image description here

like image 104
Didzis Elferts Avatar answered Nov 02 '22 20:11

Didzis Elferts