I would like to use ggplot and faceting to construct a series of density plots grouped by a factor. Additionally, I would like to a layer another density plot on each of the facets that is not subject to the constraints imposed by the facet.
For example, the faceted plot would look like this:
require(ggplot2)
ggplot(diamonds, aes(price)) + facet_grid(.~clarity) + geom_density()
and then I would like to have the following single density plot layered on top of each of the facets:
ggplot(diamonds, aes(price)) + geom_density()
Furthermore, is ggplot with faceting the best way to do this, or is there a preferred method?
One way to achieve this would be to make new data frame
diamonds2
that contains just columnprice
and then twogeom_density()
calls - one which will use originaldiamonds
and second that usesdiamonds2
. As indiamonds2
there will be no columnclarity
all values will be used in all facets.UPDATE - as suggested by @BrianDiggs the same result can be achieved without making new data frame but transforming it inside the
geom_density()
.Another approach would be to plot data without faceting. Add two calls to
geom_density()
- in one addaes(color=clarity)
to have density lines in different colors for each level ofclarity
and leave empty secondgeom_density()
- that will add overall black density line.