[R] Barplot by two variables
Marc Schwartz
marc_schwartz at comcast.net
Fri May 11 01:26:18 CEST 2007
On Thu, 2007-05-10 at 15:58 -0700, Deepayan Sarkar wrote:
> On 5/10/07, Spilak,Jacqueline [Edm] <Jacqueline.Spilak at 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
More information about the R-help
mailing list