Skip to content

preparing data for barplot()

3 messages · PIKAL Petr, Andrew Ziem

#
What is the best way to produce a barplot from my data?  I would like
the barplot to show each person with the values stacked
val1+val2+val3, so there is one bar for each person  When I use
barplot(data.matrix(realdata)), it shows one bar for each value
instead.

To post here, I created an artificical data set, but it works fine.

fakedata <- as.data.frame(list(LETTERS[1:3]))
colnames(fakedata) <- 'people'
fakedata['val1'] = abs(rnorm(3))
fakedata['val2'] = abs(rnorm(3))
fakedata['val3'] = abs(rnorm(3))
barplot(data.matrix(fakedata))

At a glance there is no substantial difference is between my fake data
and my real data.
person val1 val2 val3
1      A  221   71  175
2      B  222   85  147
people       val1     val2       val3
1      A 0.75526748 0.445386 0.09186245
2      B 0.06107566 2.008815 2.50269410
3      C 0.47171611 0.592037 0.57612168

However
person val1 val2 val3
1     NA  221   71  175
2     NA  222   85  147
Warning messages:
1: NAs introduced by coercion
2: NAs introduced by coercion

So then I converted 'person' from a list to factors, which removed the
coercision error, but barplot() still shows each bar as value instead
of a person.

My serialized() data subset is here (look at bottom half where there
are no line numbers)
http://pastebin.com/m6d1e1d79


Thanks in advance,
Andrew
#
Hi

Read what barplot does and look to your plot.

If you want each row to be plotted as stacked bar with names uder each bar 
taken from peaople variable then you need to 

transpose your matrix - barplot takes columns
plot without names - you do not want them really plotted
add names under each bar - that is what names.arg is for

barplot(t(data.matrix(fakedata[,-1])), names.arg=fakedata$people)

Regards
Petr

r-help-bounces at r-project.org napsal dne 03.03.2009 19:00:12:
http://www.R-project.org/posting-guide.html
1 day later
#
Hello Petr,

Thank you.  That works beautifully.  I searched for a way to transpose
a data frame, but you are right: barplot() wants a matrix.


Andrew
On Wed, Mar 4, 2009 at 1:49 AM, Petr PIKAL <petr.pikal at precheza.cz> wrote: