[R] Stacked Bar

Deepayan Sarkar deepayan.sarkar at gmail.com
Tue Aug 21 20:26:08 CEST 2007


On 8/21/07, Stephen Tucker <brown_emu at yahoo.com> wrote:
> I think you want to use the 'density' argument. For example:
>
> barplot(1:5,col=1)
> legend("topleft",fill=1,legend="text",cex=1.2)
> par(new=TRUE)
> barplot(1:5,density=5,col=2)
> legend("topleft",fill=2,density=20,legend="text",bty="n",cex=1.2)
>
> (if you wanted to overlay solid colors with hatching)
>
> Here's the lattice alternative of the bar graph, though the help page says
> 'density' is currently unimplemented (Package lattice version 0.16-2).

Yes, and that's unlikely to change unless grid begins to support it.

> To get
> the legend into columns, I followed the suggestion described here:
> http://tolstoy.newcastle.edu.au/R/help/05/04/2529.html
>
> Essentially I use mapply() and the line following to create a list with
> alternating 'text' and 'rect' arguments (3 times to get 3 columns).
> ===
> x <- matrix(1:75, ncol= 5)
> dimnames(x)[[2]] <- paste("Method", 1:5, sep="")
> dimnames(x)[[1]] <- paste("Row", 1:15, sep="")
>
> u <- mapply(function(x,y) list(text=list(lab=x),rect=list(col=y)),
>             x = as.data.frame(matrix(levels(as.data.frame.table(x)$Var1),
>               ncol=3)),
>             y = as.data.frame(matrix(rainbow(nrow(x)),
>               ncol=3)),
>             SIMPLIFY=FALSE)
> key <- c(rep=FALSE,space="bottom",unlist("names<-"(u,NULL),rec=FALSE))
>
> barchart(Freq ~ Var2,
>          data = as.data.frame.table(x),
>          groups = Var1, stack = TRUE,
>          col=rainbow(nrow(x)),density=5,
>          key = key )
> ===

A more transparent solution (IMO) is something like

barchart(Freq ~ Var2,
        data = as.data.frame.table(x),
        groups = Var1, stack = TRUE,
        par.settings = list(superpose.polygon = list(col=rainbow(nrow(x)))),
        auto.key = list(space = "right", columns = 2) )

-Deepayan



More information about the R-help mailing list