[R] lattice barchart sorting and coloring

Deepayan Sarkar deepayan at stat.wisc.edu
Fri Dec 13 06:15:05 CET 2002


On Thursday 12 December 2002 10:25 pm, Alexander.Herr at csiro.au wrote:
> Hi List,
>
> I am trying to produce a lattice barchart with text as labels. My data is
> ordered, but the chart sorts x labels alphabetically.

What do you mean by your data is 'ordered' ? I am guessing your x variable is 
just character strings. character variables are converted into factors before 
being plotted, and the order in which they are plotted is determined by the 
order in which they appear in the levels of that factor. By default, factor 
levels are assigned in alphabetical order, which is what you are seeing in 
barchart. For example,

> y <- c("jan", "feb", "mar")[sample(1:3, 10, rep = T)]
> y
 [1] "jan" "mar" "mar" "feb" "mar" "feb" "mar" "feb" "jan" "mar"


> factor(y) # default : alphabetical order
 [1] jan mar mar feb mar feb mar feb jan mar
Levels: feb jan mar


> factor(y, levels = unique(y))  # explicitly specified levels
 [1] jan mar mar feb mar feb mar feb jan mar
Levels: jan mar feb


> Is there any way of forcing my ordering onto the chart?

Create the factor beforehand with the ordering you want.

> Secondly, I wish to color groups of the bars based on a coded variable. Any
> way of passing these codes onto colors on the chart (panel.superpose does
> changes columns to dots).

Not doable yet, unless you write your own panel function. I have plans to 
implement this, but probably not before next year/month.

Deepayan




More information about the R-help mailing list