[R] bug/feature with barplot?
Marc Schwartz (via MN)
mschwartz at mn.rr.com
Mon Nov 14 16:59:21 CET 2005
On Mon, 2005-11-14 at 15:55 +0100, Karin Lagesen wrote:
> I have found a bug/feature with barplot that at least to me shows
> undesireable behaviour. When using barplot and plotting fewer
> groups/levels/factors(I am unsure what they are called) than the number
> of colors stated in a col statement, the colors wrap around such that
> the colors are not fixed to one group. This is mostly problematic when
> I make R figures using scripts, since I sometimes have empty input
> groups. I have in these cases experienced labeling the empty group as
> red, and then seeing a bar being red when that bar is actually from a
> different group.
>
> Reproducible example (I hope):
>
> barplot(VADeaths, beside=TRUE, col=c("red", "green", "blue", "yellow", "black"))
> barplot(VADeaths[1:4,], beside=TRUE, col=c("red", "green", "blue", "yellow", "black"))
>
> Now, I don't know if this is a bug or a feature, but it sure bugged me...:)
>
> Karin
Most definitely not a bug.
As with many vectorized function arguments, they will be recycled as
required to match the length of other appropriate arguments.
In this case, the number of colors (5) does not match the number of
groups (4). Thus, they are "out of synch" with each other and you get
the result you have.
Not unexpected behavior.
You should adjust your code and the function call so that the number of
groups matches the number of colors. Something along the lines of the
following:
col <- c("red", "green", "blue", "yellow", "black")
no.groups <- 4
barplot(VADeaths[1:no.groups, ], beside = TRUE, col = col[1:no.groups])
Now try:
no.groups <- 5
barplot(VADeaths[1:no.groups, ], beside = TRUE, col = col[1:no.groups])
no.groups <- 3
barplot(VADeaths[1:no.groups, ], beside = TRUE, col = col[1:no.groups])
HTH,
Marc Schwartz
More information about the R-help
mailing list