[R] Overlay plots from different data sets using the Lattice package

hadley wickham h.wickham at gmail.com
Tue Jan 15 02:38:59 CET 2008


On Jan 14, 2008 7:30 PM, Erin Steiner <steiner.erin at gmail.com> wrote:
> #After spending the entire day working on this question, I have
> decided to reach out for support:
>
> #I am trying to overlay a densityplot from one data set over a
> histogram of another, if I were to plot the two individually, they
> would look like:
>
> # data frame construction
>
> data.frame.A <- data.frame(rnorm(12*8), c(rep("one", 4), rep("two",
> 4), rep("three", 4)), c("red", "orange", "yellow", "green"))
> names(data.frame.A) <- c("vals", "factor.1", "factor.2")
> data.frame.B <- data.frame(rnorm(12*15), c(rep("one", 4), rep("two",
> 4), rep("three", 4)), c("red", "orange", "yellow", "green"))
> names(data.frame.B) <- names(data.frame.A)
>
> # stand alone plots
> histogram(~ vals|factor.1*factor.2, data.frame.A, type = "density")
> densityplot(~ vals | factor.1*factor.2, data.frame.B, plot.points = F)

It isn't lattice, but this is pretty easy to do with ggplot2:

install.packages("ggplot2")
library(ggplot2)

qplot(vals, ..density.., data = data.frame.A, geom="histogram", facets
= factor.1 ~ factor.2, binwidth = 1) + geom_density(data=data.frame.B)

In ggplot2, every "layer" on the plot can have a different dataset.
You can find out more about ggplot2 at http://had.co.nz/ggplot2/, but
I'm still working on the documentation for these more advanced
features.

Hadley


-- 
http://had.co.nz/




More information about the R-help mailing list