2012-04-26 38 views
0

旁边我设法将一些数据聚合到以下几点:Barplot问题

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 

我通过努力创造一个barplot那里换了个酒吧是彼此相邻,所以上面的例子一月4月将有两个酒吧(2011年和2012年)和其余的月份将只有一个代表2011年的酒吧。

我知道我必须使用beside=T,但我想我需要创建某种矩阵为了让barplot正确显示。我有一个问题想清楚这一步是什么。我有一种感觉,它可能涉及matrix,但由于某种原因,我完全被难倒了似乎是一个非常简单的解决方案。

此外,我有这样的数据:y=c('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'),我想在我的names.arg中使用。当我尝试使用上面的数据时,它会告诉我选择了未定义的列,这意味着我需要在y中使用16个变量。我怎样才能解决这个问题?

+0

我继续前进并切换列名称;我认为这是一个错字。 – joran 2012-04-26 19:54:07

回答

2

要使用barplot您需要重新安排你的数据:

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

或者你可以使用GGPLOT2有相当多的数据是:

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