Unusual legend using size mapping and density2d

ggplot2, r

Solution

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)

Problem

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

Original source