[R] Histogram colours in lattice.

Deepayan Sarkar deepayan.sarkar at gmail.com
Thu Oct 9 02:34:27 CEST 2008


On Wed, Oct 8, 2008 at 12:15 PM, Rolf Turner <r.turner at auckland.ac.nz> wrote:
>
> On 8/10/2008, at 5:16 PM, Deepayan Sarkar wrote:
>
>> On 10/7/08, Rolf Turner <r.turner at auckland.ac.nz> wrote:
>>>
>>>  I am trying to do a histogram lattice plot and I would like the
>>>  histogram to be filled with a different colour in each panel.
>>>
>>>  Note:  I want every bar in each histogram to be the same colour,
>>>  but that there should be different colours *between* histograms.
>>>
>>>  Can't seem to get this to work.  I thought that something like
>>>  the following would be a goer:
>>>
>>>  set.seed(42)
>>>  X <- rnorm(200)
>>>  A <- factor(sample(letters[1:5],200,TRUE))
>>>  DF <- data.frame(x=X,a=A)
>>>  print(histogram(~x|a,data=DF,col=2:6,type="count",
>>>  panel=function(x,...,subscripts,col) {
>>>        panel.histogram(x,...,col=col[subscripts])
>>>  }))
>>>
>>>  However it somewhat mysteriously colours the first bar/rectangle
>>>  of the histogram appropriately in the last three panels, leaving
>>>  all of the others blank, and leaves all bars blank in the first
>>>  two panels.
>>
>> That's because you are ending up with 'col[subscripts]' being a
>> vector, most elements of which are NA.
>>
>>>  Can I do what I want?  How?
>>
>> print(histogram(~x|a,data=DF,col=2:6,type="count",
>>  panel=function(x,...,col) {
>>     panel.histogram(x,...,col=col[packet.number()])
>> }))
>
>        Works like a charm.  Thanks very much.  I guess I thought
>        I roughly understood what ``subscripts'' meant, and it seems
>        I don't understand at all.  And I didn't know *anything* about
>        ``packet.number()''.  It would seem that I need to read your
>        book --- are these things explained there?

Yes, but note that your use case is somewhat nonstandard, and is not
one directly addressed either in my book, or in the older Trellis
literature (as far as I know).

packet.number() is explained adequately in the help page. The
subscripts concept is very useful, but definitely poses a challenge to
many users (it took me a while to understand all its implications
too). I don't know how to explain it in simple terms, except to say
that it is the per-panel row indices with respect to the original data
source. For example,


> foo <- xyplot(10:1 ~ 1:10 | gl(2, 1, 10), subscripts = TRUE)
> str(trellis.panelArgs(foo, 1))
List of 3
 $ x         : int [1:5] 1 3 5 7 9
 $ y         : int [1:5] 10 8 6 4 2
 $ subscripts: int [1:5] 1 3 5 7 9
> str(trellis.panelArgs(foo, 2))
List of 3
 $ x         : int [1:5] 2 4 6 8 10
 $ y         : int [1:5] 9 7 5 3 1
 $ subscripts: int [1:5] 2 4 6 8 10

-Deepayan



More information about the R-help mailing list