[R] bar charts

Roger Bivand Roger.Bivand at nhh.no
Fri Dec 10 12:14:48 CET 2004


On Fri, 10 Dec 2004, Leonardo Lami wrote:

> Hi,
> I'd like plot a bar graphic of a array.
> I'd like to have the values of the single columns as juxtaposed bars (like in 
> "barplot" with beside=TRUE) and I'd like to have the values of the single 
> columns expressed  like percentage of the sum of the coloumn.
> In this way all the bars are composed by the sum of the percentage of the 
> values of a coloumn (with different colors) and all they have 100% value. 

If I understand you correctly, something like:

> tab <- xtabs(breaks ~ tension + wool, data = warpbreaks)
> barplot(tab, beside=TRUE)
> colSums(tab)
  A   B 
838 682 

is what you have, and what you want is:

> barplot(apply(tab, 2, function(x) (100*x)/sum(x)), beside=TRUE)
> colSums(apply(tab, 2, function(x) (100*x)/sum(x)))
  A   B 
100 100 

You'll need a good explanatory caption, though, when the column sums are 
different.

> 
> Thanks
> Leonardo Lami
> 
> 

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Breiviksveien 40, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 93 93
e-mail: Roger.Bivand at nhh.no




More information about the R-help mailing list