2016-07-11 96 views
0

我有一个数据帧“数”说是这样的:barplot多个聚合

#     Date  Code Number_of_events 
#1     01-04 022003  5 
#2     01-06 022003  9 
#3     01-08 022003  3 
#4     01-11 022003  2 
#5     01-13 022003  5 
#... 
#3754    03-11 396001  4 
#3755    03-16 396001  4 
#3756    03-21 396001  17 
#3757    03-22 396001  23 
#3758    03-23 396001  3 

,我得到了按日期和编号骨料DF的结果:

count<-aggregate(.~ Date+Code,data=df,FUN=sum) 

我想做的事情每个代码是一系列(因此是彩色条)的事件数量(y)与日期(x)的barplot。了解事件在相同的日期不会发生。

有人能帮助我吗?谢谢

回答

1

你可以使用ggplot2包,里面包含了方便geom_bar()功能。

模拟一些数据:

# simulate some data 
N <- 100 
df <- data.frame(Date = sample(seq(as.Date("2000/1/1"), by = "month", length.out = 48), N, T), 
        Code = sample(c(022003, 396001, 441002), size = N, replace = T), 
        Number_of_events = rpois(N, 5)) 

#aggregate 
count <- aggregate(.~ Date+Code,data=df,FUN=sum) 

这是绘图:

library(ggplot2) 

ggplot(count, aes(x=Date, y=Number_of_events)) + 
    geom_bar(aes(fill=as.factor(Code)), color="black", stat="identity", position="stack") 

enter image description here

1

我们可以使用barplot

barplot(xtabs(Number_of_events~Code + Date, df), 
       beside = TRUE, legend = TRUE, col = c("red", "blue")) 

或者使用ggplot

library(dplyr) 
library(ggplot2) 
df %>% 
    group_by(Date, Code) %>% 
    summarise(Number_of_events = sum(Number_of_events)) %>% 
    ggplot(., aes(x= Date, y = Number_of_events)) + 
     geom_bar(aes(fill= factor(Code)), position = "dodge", stat = "identity")