2012-08-23 31 views
5

我有一个很好的。我现在想了很久。我有这个数据集,这个数据集可能很大。我想根据每个月的前5位最高计数来绘制一个ggplot堆栈栏。例如,对于1 //2012分之1,该higest计数是I,G,F,d和Eggplot堆栈条形图前5每月

DF

Date Desc count 
1/1/2012 A 10 
1/1/2012 B 5 
1/1/2012 C 7 
1/1/2012 D 25 
1/1/2012 E 19 
1/1/2012 F 30 
1/1/2012 G 50 
1/1/2012 H 10 
1/1/2012 I 100 
2/1/2012 A 10 
2/1/2012 B 5 
2/1/2012 C 7 
2/1/2012 D 25 
2/1/2012 E 19 
2/1/2012 F 30 
2/1/2012 G 50 
2/1/2012 H 10 
2/1/2012 I 100 
3/1/2012 A 1 
3/1/2012 B 4 
3/1/2012 C 5 
3/1/2012 D 6 
3/1/2012 E 6 
3/1/2012 F 7 
3/1/2012 G 8 
3/1/2012 H 5 
3/1/2012 I 10 

我有这样的事情,但这个图表的所有值:

ggplot(df, aes(Date, count))+ geom_bar(aes(fill=Desc), stat="identity", position="stack") + theme_bw() 

回答

4

你必须先子集数据:

library(plyr) 
library(ggplot2) 
df_top <- ddply(df, .(Date), 
       function(x) head(x[order(x$count, decreasing = TRUE),], 5)) 
ggplot(df_top, aes(Date, count))+ 
    geom_bar(aes(fill=Desc), stat="identity", position="stack") + 
    theme_bw() 

enter image description here

+0

我没有得到相同的结果,你怎么得到x? – user1471980

+0

你是什么意思?我做的匿名函数? –