Re: [R] Barplot by two variables

From: Marc Schwartz <marc_schwartz_at_comcast.net>
Date: Thu, 10 May 2007 18:26:18 -0500

On Thu, 2007-05-10 at 15:58 -0700, Deepayan Sarkar wrote:
> On 5/10/07, Spilak,Jacqueline [Edm] <Jacqueline.Spilak@ec.gc.ca> wrote:
> > Hi all
> > I have a bit of a problem. I want to make a barplot of some data. My
> > data is of a score that is separated by year and by a limit (above 3 and
> > below 3 to calculate the score).
> > Year Limit HSS
> > 1999 ALT 0.675
> > 1999 VFR 0.521
> > 2000 ALT 0.264
> > 2000 VFR 0.295
> >
> > I would like to have a barplot with year on the x axis and HSS on the y
> > axis and the two limits as two different colors to show the difference.
> > Using (dataset$HSS, col=c("green","purple")) I get some of the plot
> > but I don't know how to get labels on the bottom for each year and I
> > can't get a legend for my barplot. Not really sure what I am doing
> > wrong but any help would be much appreciated.

>
> Here's one solution using the lattice package:
>
> library(lattice)
> barchart(HSS ~ factor(Year), data = dataset, origin = 0,
> groups = Limit, auto.key = TRUE)

And here is one using barplot():

> DF

  Year Limit HSS

1 1999   ALT 0.675
2 1999   VFR 0.521
3 2000   ALT 0.264
4 2000   VFR 0.295


barplot(matrix(DF$HSS, ncol = 2), beside = TRUE, 
        names.arg = unique(DF$Year), 
        legend.text = unique(DF$Limit)


Note that I convert DF$HSS to a two column matrix to enable using the built-in 'beside' argument in barplot() for the bar pairings, much like Deepayan has used the formula in barchart() above.

Then it is a matter of getting the unique values for both the Years and the Limits to use them for the x axis labels and the legend text.

HTH, Marc Schwartz



R-help_at_stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 10 May 2007 - 23:31:51 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 11 May 2007 - 00:32:04 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.