# [R] Lattice: Plotting two densities on the same plot(s)?

Deepayan Sarkar deepayan at stat.wisc.edu
Wed Jan 8 05:56:03 CET 2003

```On Tuesday 07 January 2003 09:45 pm, Olivia Lau wrote:
> I am trying to plot two density lines on the same graph.  Using the
> functions on the base package, I would go:
>
> plot(density(x), col = 1)
> lines(density(y), col = 2)
>
> And I get two distinct (one-bump) density lines.  When I try to do it
> using lattice, I get two two-humped lines.  (In other words, I think the
> smoothing function is taking the next set of data points and smoothing them
> in the same function as the prior set.)
>
> Using:
>
> library(nlme)
> library(grid)

You don't seem to be using nlme anywhere. And

library(lattice)

> Let:
>
> democrat <- rnorm(100, 0.3, 0.1)
> republican <- rnorm(100, 0.5, 0.1)
> state <- c("Delaware")
> temp1 <- as.data.frame(cbind(state, democrat, republican))
>
> democrat <- rnorm(100, 0.5, 0.1)
> republican <- rnorm(100, 0.7, 0.1)
> state <- c("Pennsylvania")
> temp2 <- as.data.frame(cbind(state, democrat, republican))
>
> data1 <- rbind(temp1, temp2)

This is probably not what you wanted, since the varibles 'republican' and
'democrat' in data1 have now become factors. (When you use them in
panel.densityplot below, you are using not the ones in the data frame, but
rather the ones in your global environment.)

> What I'm doing right now is:
>
> densityplot(~ democrat | state, data = data1,
>   xlim = c(0, 1), ylim = c(0, 10),
>   panel = function(x) {
>   panel.densityplot(republican,  col = "red")
>   panel.densityplot(democrat, col = "black")
>   })
>
> What should I do to draw two separate density plots on the same lattice
> device?

The recommended way needs the data frame to structured differently. Let's say
you have the 4 sets of numbers

del.democrat <- rnorm(100, 0.3, 0.1)
del.republican <- rnorm(100, 0.5, 0.1)
penn.democrat <- rnorm(100, 0.5, 0.1)
penn.republican <- rnorm(100, 0.7, 0.1)

Create the data frame as

data1 <- expand.grid(replication = 1:100,
party = c("democrat", "republican"),
state = c("Delaware", "Pennsylvania"))

data1\$x <- c(del.democrat, del.republican,
penn.democrat, penn.republican)

Then,

densityplot(~ x | state, data1, groups = party, panel = "panel.superpose")

should give you what you want.

Deepayan

```