Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: Is there a way to overlay a single plot to all facets in a ggplot

Tags:

r

ggplot2

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?

like image 319
skleene Avatar asked Apr 05 '13 13:04

skleene


People also ask

What does Facet_wrap do in Ggplot?

facet_wrap() makes a long ribbon of panels (generated by any number of variables) and wraps it into 2d. This is useful if you have a single variable with many levels and want to arrange the plots in a more space efficient manner.

What is the difference between Facet_wrap and Facet_grid?

The facet_grid() function will produce a grid of plots for each combination of variables that you specify, even if some plots are empty. The facet_wrap() function will only produce plots for the combinations of variables that have values, which means it won't produce any empty plots.

What are facets in Ggplot?

The facet approach partitions a plot into a matrix of panels. Each panel shows a different subset of the data. This R tutorial describes how to split a graph using ggplot2 package. There are two main functions for faceting : facet_grid()


1 Answers

One way to achieve this would be to make new data frame diamonds2 that contains just column price and then two geom_density() calls - one which will use original diamonds and second that uses diamonds2. As in diamonds2 there will be no column clarity all values will be used in all facets.

diamonds2<-diamonds["price"]
ggplot(diamonds, aes(price)) + geom_density()+facet_grid(.~clarity) + 
     geom_density(data=diamonds2,aes(price),colour="blue")

enter image description here

UPDATE - as suggested by @BrianDiggs the same result can be achieved without making new data frame but transforming it inside the geom_density().

ggplot(diamonds, aes(price)) + geom_density()+facet_grid(.~clarity) +
     geom_density(data=transform(diamonds, clarity=NULL),aes(price),colour="blue")

Another approach would be to plot data without faceting. Add two calls to geom_density() - in one add aes(color=clarity) to have density lines in different colors for each level of clarity and leave empty second geom_density() - that will add overall black density line.

ggplot(diamonds,aes(price))+geom_density(aes(color=clarity))+geom_density()

enter image description here

like image 157
Didzis Elferts Avatar answered Sep 27 '22 20:09

Didzis Elferts