2016-07-11 121 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")