grouped barplot issue

7 views
Skip to first unread message

Dan

unread,
Jun 29, 2009, 3:32:20 PM6/29/09
to Bay Area R Helpers
I've made grouped barplots before and generally I plot the results of
table().

I want to create a grouped barplot from two vectors of integers. As an
example

vector1 <- c(100, 200, 300)
vector2 <- c(50, 250, 300)

I'd like bars grouped by element number vector1[i] grouped with vector2
[i].

And I want the height of the bars to be equivalent to the value of the
element.

I've tried as.table() and putting them in as a matrix, but there's
some kind of bug. I've tried a bunch of things Anyone have any ideas?

Thanks a lot.

Mark Knecht

unread,
Jun 29, 2009, 4:21:08 PM6/29/09
to Dan, Bay Area R Helpers
Not totally sure I understand exactly what you're after but somehow
this portion of the barplot example seems close:

require(grDevices) # for colours
tN <- table(Ni <- stats::rpois(100, lambda=5))
#- type = "h" plotting *is* 'bar'plot
lines(r, tN, type='h', col='red', lwd=2)
tot <- colMeans(VADeaths)
text(mp, tot + 3, format(tot), xpd = TRUE, col = "blue")
title(main = "Death Rates in Virginia", font.main = 4)

hh <- t(VADeaths)[, 5:1]
mybarcol <- "gray20"
mp <- barplot(hh, beside = TRUE,
col = c("lightblue", "mistyrose",
"lightcyan", "lavender"),
legend = colnames(VADeaths), ylim= c(0,100),
main = "Death Rates in Virginia", font.main = 4,
sub = "Faked upper 2*sigma error bars", col.sub = mybarcol,
cex.names = 1.5)

I think your job is to get vector1 and vector2 into hh.n If it helps
VADeaths is a matrix.

Hope this helps,
Mark

Ted Dunning

unread,
Jun 29, 2009, 7:05:33 PM6/29/09
to Bay Area R Helpers

Barplot is a bit fussy and wants a matrix. It would be nice if it
accepted a data.frame. I tend to use a data frame anyway and just
convert it and possible transpose it at the last minute.

> vector1 <- c(100, 200, 300)
> vector2 <- c(50, 250, 300)
> barplot(as.matrix(data.frame(x=vector1, y=vector2)), beside=T)
> barplot(t(as.matrix(data.frame(x=vector1, y=vector2))), beside=T)

This last one gives the grouping you want, but lacks good labeling.
The labels aren't too hard to add in, but a legend is even easier:

> barplot(t(as.matrix(data.frame(x=vector1, y=vector2))), beside=T, legend.text=c("x", "y"), args.legend=list(x=2, y=250))
Reply all
Reply to author
Forward
0 new messages