[R] barplot dataframes w/ varying dimensions
Marc Schwartz
MSchwartz at mn.rr.com
Fri Jun 9 13:14:34 CEST 2006
On Fri, 2006-06-09 at 06:05 -0500, Marc Schwartz wrote:
> On Fri, 2006-06-09 at 11:26 +0100, Albert Vilella wrote:
> > Hi all,
> >
> > I would like to do a barplot of a dataframe like this one:
> >
> > alfa beta gamma delta
> > qwert 56.5 58.5 56.5 58.5
> > asdfg 73.0 73.0 43.0 73.0
> > zxcvb 63.0 63.0 43.0 63.0
> > yuiop 63.0 63.0 43.0 63.0
> >
> > with the labels of the rows and columns.
> >
> > I would like to have something that works for dataframes with varying
> > dimensions, and so far I haven't found any way to do it.
> >
> > What would be the best way to do that?
> >
> > Thanks in advance,
> >
> > Albert.
>
> barplot() requires the 'height' argument to be a vector or matrix, so
> you need to coerce the data frame:
>
> barplot(as.matrix(DF))
>
> or
>
> barplot(as.matrix(DF), beside = TRUE)
>
> depending upon the format you prefer.
I forgot to note that you will get the colnames(DF) to label the
groupings by default, but to get the rownames(DF) as well, you might do
that with a legend:
barplot(as.matrix(DF), legend.text = rownames(DF),
ylim = c(0, max(colSums(DF)) * 1.4))
or
barplot(as.matrix(DF), beside = TRUE, legend.text = rownames(DF),
ylim = c(0, max(DF) * 1.4))
Note that I have adjusted the range of the y axis in each case to make
room for the legend in the upper right hand corner.
You would have more flexibility in legend formatting by using legend()
separately. See ?legend for more information.
HTH,
Marc
More information about the R-help
mailing list