Wednesday, August 5, 2009

Multiple lattice plots

Here's Owen's trick for displaying multiple lattice dotplots:

In the reshape package, the function melt() allows you to reshape data into variable/value columns, on one or more "id" column(s):


> library(reshape)
> library(lattice)
> d <- data.frame(a=rnorm(10), b=rnorm(10), c=rnorm(10), cond=factor(sample(1:2,10,replace=TRUE)))

> d
a b c cond
1 0.06927895 0.98947264 1.7256042 2
2 -2.02604891 -0.33003778 -0.6595201 1
3 0.38082836 -0.98114426 1.5448757 2
4 -2.73939190 -1.30930261 0.1118557 1
5 0.37405184 -0.45263384 1.0484490 1
6 -0.68747094 -0.78446749 0.3484745 2
7 0.13011011 1.01275070 -0.5005770 1
8 -0.33158390 1.38201954 0.3096848 1
9 0.07920194 0.05604219 -1.8579733 2
10 -0.49055146 -1.17780285 0.6850589 1

> melt(d, id="cond")
cond variable value
1 2 a 0.06927895
2 1 a -2.02604891
3 2 a 0.38082836
4 1 a -2.73939190
5 1 a 0.37405184
6 2 a -0.68747094
7 1 a 0.13011011
8 1 a -0.33158390
9 2 a 0.07920194
10 1 a -0.49055146
11 2 b 0.98947264
12 1 b -0.33003778
13 2 b -0.98114426
14 1 b -1.30930261
15 1 b -0.45263384
16 2 b -0.78446749
17 1 b 1.01275070
18 1 b 1.38201954
19 2 b 0.05604219
20 1 b -1.17780285
21 2 c 1.72560425
22 1 c -0.65952015
23 2 c 1.54487566
24 1 c 0.11185573
25 1 c 1.04844895
26 2 c 0.34847452
27 1 c -0.50057699
28 1 c 0.30968476
29 2 c -1.85797331
30 1 c 0.68505890

> stripplot(value~cond|variable,melt(d, id="cond"),scales=list(relation="free"))


Setting parameter as.table=TRUE will plot from top left to bottom right.