thequerist
thequerist

Reputation: 1824

Barplot beside issue

I have managed to aggregate some data into the following:

   Month Year Number
1     1  2011   3885
2     2  2011   3713
3     3  2011   6189
4     4  2011   3812
5     5  2011    916
6     6  2011   3813
7     7  2011   1324
8     8  2011   1905
9     9  2011   5078
10   10  2011   1587
11   11  2011   3739
12   12  2011   3560
13    1  2012   1790
14    2  2012   1489
15    3  2012   1907
16    4  2012   1615

I am trying to create a barplot where the bars for the months are next to each other, so for the above example January through April will have two bars (one for 2011 and one for 2012) and the remaining months will only have one bar representing 2011.

I know I have to use beside=T, but I guess I need to create some sort of matrix in order to get the barplot to display properly. I am having an issue figuring out what that step is. I have a feeling it may involve matrix but for some reason I am completely stumped to what seems like a very simple solution.

Also, I have this data: y=c('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec') which I would like to use in my names.arg. When I try to use it with the above data it tells me undefined columns selected which I am taking to mean that I need 16 variables in y. How can I fix this?

Upvotes: 1

Views: 6275

Answers (1)

joran
joran

Reputation: 173577

To use barplot you need to rearrange your data:

dat <- read.table(text = "   Month Year Number
1     1  2011   3885
2     2  2011   3713
3     3  2011   6189
4     4  2011   3812
5     5  2011    916
6     6  2011   3813
7     7  2011   1324
8     8  2011   1905
9     9  2011   5078
10   10  2011   1587
11   11  2011   3739
12   12  2011   3560
13    1  2012   1790
14    2  2012   1489
15    3  2012   1907
16    4  2012   1615",sep = "",header = TRUE)

y <- c('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')

barplot(rbind(dat$Number[1:12],c(dat$Number[13:16],rep(NA,8))),
        beside = TRUE,names.arg = y)

enter image description here

Or you can use ggplot2 with the data pretty much as is:

dat$Year <- factor(dat$Year)
dat$Month <- factor(dat$Month)
ggplot(dat,aes(x = Month,y = Number,fill = Year)) + 
    geom_bar(position = "dodge") + 
    scale_x_discrete(labels = y)

enter image description here

Upvotes: 5

Related Questions