[R] barplot as Trellis graphic

Charilaos Skiadas cskiadas at gmail.com
Thu Mar 27 19:33:11 CET 2008


On Mar 27, 2008, at 1:47 PM, Agustin Lobo wrote:

> Thanks, it was a matter of reshaping the data matrix as I usually have
> it, ie:
> datos <-
> data.frame(x=abs(round(rnorm(100,10,5))),y=abs(round(rnorm 
> (100,2,1))),f=factor(round(runif(100,1,3))))
>
> to become:
>
> datos2 <-
> data.frame(V1=c(datos[,1],datos[,2]),"VAR"=c(rep("x",100),rep("y", 
> 100)),f=factor(c(datos[,3],datos[,3])))
>
> and then
> require(lattice)
> barchart(V1~VAR|f,data=datos2)
>
> I get horizontal lines in the bars that I do not understand, though.

In order to understand the lines , you should ask: What does the  
height of each bar correspond to? As you have set things up, the "x"  
bar in panel "1" should somehow correspond to the all values:

datos2$V1[datos2$VAR=="x" & datos2$f==1]
[1] 15 13 14  1 18 14  8 12  7 19 10  1  5 14  7  9 14  7  5 10  6 12  
10 11 11  7 15
[28]  9  4 12 17 10  4  5


So you should ask yourself, how you expect R to produce a single  
column, which in some sense corresponds to just one single number,  
its height, from these different values. My guess is that you want R  
to show you just the mean on each group. For me this is not a  
barplot, but anyway. What happens in the barplot you have now, I  
think, is this that R will start by constructing a bar with height  
15, then put on it a bar of height 13, then on it a bar of height 14  
and so on. So the lines you see account for the boxes that survive:

 > x<-datos2$V1[datos2$VAR=="x" & datos2$f==1]
 > unique(cummax(rev(x)))
[1]  5 10 17 19


I would recommend using boxplots instead of "barplots only showing  
the means". If you really want barplots of the means, I think you can  
do the following:

datos3 <- with(datos2, aggregate(x=V1, by=list(VAR=VAR,f=f), mean))
barchart(x~VAR|f, datos3)

Another option would be ggplot2 I think, but I'll let someone  
knowledgeable with that package speak up.

> Agus
>

Haris Skiadas
Department of Mathematics and Computer Science
Hanover College



More information about the R-help mailing list