[R] help on barplots

Marc Schwartz MSchwartz at mn.rr.com
Mon Dec 19 15:05:21 CET 2005


On Mon, 2005-12-19 at 12:27 +0100, BjÃ¶rn Rogell wrote:
> Hello, I am a beginner with R and I would need some help with doing
> barplots.
> My problem is that I would like to include both diffrent colors of the
> bars 
> and  precence/absence of shading lines in the barplots. When reading
> in the 
> help file about the "col" command it states:
> 
> col: a vector of colors for the bars or bar components. By
>            default, grey is used if 'height' is a vector, and a
>            gamma-corrected grey palette if 'height' is a matrix.
> 
> It seems like the default is to color the bar components, when I add
> both 
> col and density the shading lines gets the colors in the col vector.
> What I 
> would need is diffrent colors of the bars and black shading lines.
> How could I solve this problem?
> Thanksful for answer/ BjÃ¶rn Rogell
> 
> 
>  > meanbufoAN
>      TR101     TR203     TR302     TR404     TR509     TR611
> TR710 
> TR812
> 12.329885 12.712815 12.115556 12.570500 11.580300 11.920851 10.094532
> 9.854988
> 
> barplotANbufo<-barplot(meanbufoAN,ylim=c(0,15),col=c("white","lightgrey","white",
>
> "lightgrey","white","lightgrey","white","lightgrey"),
>
> names.arg=c("1","2","2","4","5","6","7","8"),density=c(0,0,12,12,0,0,12,12),xlab="", 
> ylab="Length")


The problem here is that the bars are drawn within barplot() using
rect(), which does not allow for both bar colors and line shadings
simultaneously.  However, there is a workaround.

This involves drawing the initial barplot using the colors that you want
for the bars and then using barplot a second time, with 'add = TRUE' and
'col = NA'. The former will 'overplot' the initial barplot without
clearing the plot device first. The latter will draw the shading lines,
but using a transparent background color, so that it retains the initial
bar colors.

Thus:

barplotANbufo <- barplot(meanbufoAN, ylim = c(0, 15),
                         col = c("white", "lightgrey"),
                         names.arg = c(1, 2, 2, 4:8),
                         xlab="", ylab="Length")

barplot(meanbufoAN, ylim = c(0, 15), col = NA,
        density = rep(c(0, 12), 2, each = 2),
        axes = FALSE, add = TRUE)

Note also some efficiencies in the specification of the colors (which
will be recycled), names.arg (presuming that the '2' should be there
twice) and density in the second call using rep().

HTH,

Marc Schwartz




More information about the R-help mailing list