Reputation: 711
I'm trying to replicate a conditional density plot as shown in the docs for stat_density, but I need to do it with ggplot and not qplot because I need to facet the plot. However, my data has unequal numbers of rows in each facet, and when I plot it, I get weird results. Here's an MRE:
test.df = data.frame(model=c(rep("A",100),rep("B",50),rep("C",20)),
as.factor(cnt=c(rbinom(100,1,0.5),rbinom(50,1,0.5),rbinom(20,1,0.5))),
xvar=c(seq(1,100),seq(1,50),seq(1,20)))
# This works fine, ignoring the model facets.
ggplot(test.df,aes(x=xvar,y=..count..,fill=cnt)) + geom_density(position="fill")
# Something's wrong with this one.
ggplot(test.df,aes(x=xvar,y=..count..,fill=cnt)) + geom_density(position="fill") +
facet_wrap(~model)
Here's an example of what it looks like ignoring the model (and it looks the same if you subset and plot each group individually):
vs with faceting:
Any thoughts on what I might be doing wrong here?
edit: this is with R 2.15.1 / Rstudio 0.97.314 under OSX 10.8.2, ggplot2 0.9.3.1
Upvotes: 1
Views: 2071
Reputation: 115392
The problems arise because it doesn't really make sense to estimate the density when you are extrapolating the x
variable. (the limits for model = B are [0,50], and for model=C are [0,20]
If you set scales='free_x'
then you won't be forcing ggplot
to do something silly.
ggplot(test.df,aes(x=xvar,y=..count..,fill=cnt)) +
geom_density(position = "fill") +
facet_wrap(~model,scales = 'free_x')
You could alternatively pass trim = TRUE
to geom_density
(and thus stat_density
), which would trim to the range of the observed data when calculating (and plotting) the densities
ggplot(test.df,aes(x=xvar,y=..count..,fill=cnt)) +
geom_density(position="fill",trim = TRUE) +
facet_wrap(~model)
Perhaps there should be some kind of warning regarding the nonsense results in the original attempt, but I think this may be covered by fortune(15)
library(fortunes)
fortune(15)
## It really is hard to anticipate just how silly users can be.
## -- Brian D. Ripley
## R-devel (October 2003)
Upvotes: 4