每月前五个堆叠条形图,使用ggplot

5
我有一个好主意。我已经思考了很长时间了。我有一个数据集,这个数据集可能非常大。我想要根据每个月的前5个最高计数来制作一个ggplot堆栈图。例如,对于2012年1月1日,最高计数将是I,G,F,D和E。
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()
1个回答

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


我没有得到相同的结果,你是怎么得到x的? - user1471980
你是什么意思?我制作的匿名函数? - Luciano Selzer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接