I want to create a ggplot in which a statistical parameter varies according to an aesthetically mapped factor. Specifically, I'd like to create a contour plot using stat_density2d(), I'd like to to map a discrete factor to the color, and I'd like to specify different break values for each factor level.
Here's a minimal working example:
d <- data.frame(x=c(rnorm(500), rnorm(500, 2)), y=rnorm(1000), z=c(rep("a", 500), rep("b", 500)))
ggplot(d, aes(x, y, fill=z)) +
stat_density2d(breaks=.05, geom="polygon", alpha=.5)
This is what I'm going for except the breaks are identical across factors. I'm looking for a way to specify different break values for each factor. One way to do that would be to create a separate layer for each factor:
ggplot() +
stat_density2d(data=d[d$z=="a",], aes(x, y), breaks=.05, geom="polygon", alpha=.5, fill="red") +
stat_density2d(data=d[d$z=="b",], aes(x, y), breaks=.1, geom="polygon", alpha=.5, fill="blue")
But this isn't workable because I lose the legend and it's too cumbersome for cases with more than two factor levels.
I'd like to combine the strengths of the above two cases. I'm almost positive I've seen a way to accomplish what I'm trying to do, but can't seem to find it now that it's relevant. Anybody have thoughts on a possible solution?