Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot to stack bar graph top 5 for each month

Tags:

r

ggplot2

I have a good one. I've thinking about this a long time now. I have this data set and this data set could be be huge. I would like to graph a ggplot stack bar based on top 5 higest count for each month. For example, for 1//1/2012, the higest counts would be I, G, F, D and 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

I have something like this but this graphs all of the values:

 ggplot(df, aes(Date, count))+ geom_bar(aes(fill=Desc), stat="identity", position="stack") + theme_bw()
like image 649
user1471980 Avatar asked Oct 06 '22 20:10

user1471980


1 Answers

You have to subset the data first:

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

like image 193
Luciano Selzer Avatar answered Oct 10 '22 02:10

Luciano Selzer