[R] Barplot errors in MASS script

Uwe Ligges ligges at statistik.uni-dortmund.de
Thu Jan 1 20:09:52 CET 2004

v.demart at libero.it wrote:
> Reading "Modern Applied Statististics with S" and trying the corresponding
> examples both in the book and in ../lib/R/library/MASS/script, I'm now trying
> chapter 4 plotting bars with the following code on a linux box with R 1.8.1:
> ----------------------
> library(MASS)
> library(lattice)
> options(echo=T, width=65, digits=5)
> lung.deaths <- aggregate(ts.union(mdeaths, fdeaths), 1)
> barplot(t(lung.deaths), names = dimnames(lung.deaths)[[1]],
>         main = "UK deaths from lung disease")
> if(interactive())
>     legend(locator(1), c("Males", "Females"), fill = c(2, 3))
> -----------------------
> The legend doesn't look correct with respect to the picture at page 72 of the
> book for two reasons:
> 1) The legend has a transparent background while in the book is "correctly"
> opaque (and, above all, this is the background I expect!);

Set the  argument bg = "white"

> 2) One of the two variables is represented in the legend with a different colour
> from the same variable in the bars plot (green instead of yellow)

Use heat.colors() (barplot() uses it to generate the colors).

> How could I set 1 and 2 right?

   legend(locator(1), c("Males", "Females"), fill = heat.colors(2),
       bg = "white")

That points us to a documentation bug in ?legend, whioch tells us in its 
Arguments section:

bg  the background color for the legend box. (Note that this is only 
used if bty = "n".)

Obviously, it is used if bty = "o", but *not* if "n".

Uwe Ligges

> Thanks for your help
> Vittorio
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help

More information about the R-help mailing list