r - ggplot2: can a non-aesthetic parameter vary by factor? -
i want create ggplot in statistical parameter varies according aesthetically mapped factor. specifically, i'd create contour plot using stat_density2d(), i'd to map discrete factor color, , i'd specify different break values each factor level.
here's 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 i'm going except breaks identical across factors. i'm looking way specify different break values each factor. 1 way create separate layer 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 isn't workable because lose legend , it's cumbersome cases more 2 factor levels.
i'd combine strengths of above 2 cases. i'm positive i've seen way accomplish i'm trying do, can't seem find it's relevant. have thoughts on possible solution?
remebered couple of years ago - taking solution directly kohske's answer
# data set.seed(1) d <- data.frame(x=c(rnorm(500), rnorm(500, 2)), y=rnorm(1000), z=c(rep("a", 500), rep("b", 500))) library(plyr) library(ggplot2) hls <- mapply(function(x, b) stat_density2d(data = x, breaks = b, geom="polygon", alpha=.5), dlply(d, .(z)), c(0.05, 0.1)) ggplot(d, aes(x, y, fill=z)) + hls + scale_fill_manual(values=c("red", "blue"))
# compare 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")
Comments
Post a Comment