[R] barchart with 3 Arguments

Jim Lemon jim at bitwrit.com.au
Wed Aug 29 12:56:14 CEST 2012


On 08/29/2012 01:05 AM, Geophagus wrote:
> Hi @ all,
> I have a problem concerning the barplot (barchart lattice) of a dataframe. I
> work with the attached dataframe.
> When I try to plot this dataframe  I only get two rows plottet. When I try
> to plot the whole dataframe, there is message, that it is 'height' must be a
> vector or a matrix.
> On the y-axis, the "amount_cattle" should be displayed and on the x-axis the
> "year" and the "country" so that I can compare the amount over the years in
> each country. Each country on the x-axis needs 4 bars (2000-2003).
> I hope you can help me.
> Thanks a lot
> geophagus
>
Hi geophagus,
You seem to want to plot the amount_cattle values for years within 
countries. You can do this with the "barplot" function:

amount_cattle<-matrix(sample(10:50,16),nrow=4)
colnames(amount_cattle)<-
  c("Muckravia","Blotinsk","Overthar","Fumingo")
rownames(amount_cattle)<-2000:2003
barpos<-barplot(amount_cattle,beside=TRUE)
legend(4,45,2000:2003,fill=gray(c(0.2,0.4,0.6,0.8)))

You can also nest the values by year within the average values for 
countries by reshaping the amount_cattle matrix to this form:

newcattle
    ncattle   country year
1       21 Muckravia 2000
2       19  Blotinsk 2000
3       40  Overthar 2000
4       27   Fumingo 2000
5       46 Muckravia 2001
6       38  Blotinsk 2001
7       39  Overthar 2001
8       48   Fumingo 2001
9       33 Muckravia 2002
10      34  Blotinsk 2002
11      35  Overthar 2002
12      23   Fumingo 2002
13      16 Muckravia 2003
14      30  Blotinsk 2003
15      14  Overthar 2003
16      32   Fumingo 2003

library(plotrix)
barNest(ncattle~country+year,newcattle,FUN="mean",
  col=list("lightgray",rainbow(4),
  c("wheat","lightgreen","yellow","thistle")))

Jim




More information about the R-help mailing list