How can I get the same plot without an intermediate step of aggregating the amount?

How can I get the same plot without intermediate calculation of the aggregate column.

I have this data:

set.seed(1234) dat <- data.frame(month = gl(3,1,20), family= gl(5,1,20), amount= sample(1:3,20,rep=TRUE)) 

Using this code, I get a barcode. Where is each bar, this is the sum of the amount for family and for months. I first create a new VG aggegate column.

 ## I am using data.table , you can get it by ddply also library(data.table) dd <- data.table(dat) hh <- dd[,sum(amount),by=list(month,family)] 

Then I use this code:

 ggplot(data=hh,aes(x=month,y=V1,fill=family))+ geom_bar(stat = "identity") 

To get this plot:

enter image description here

This works, but I want a simpler method. I think, using the stat_sum methods or other ggplot2 methods, I can do this without an intermediate aggregation step. something like that:

  ## don't run this doesn't work ggplot(data=dat,aes(x=month,y=amount,fill=family))+ geom_bar(stat = "sum") 
+6
source share
2 answers
 ggplot(data=dat,aes(x=month,y=amount,fill=family,group=family))+ geom_bar(stat = "summary",fun.y=sum) 

enter image description here

+7
source

I found in the mailing list in R that there is an argument weight= , which can be used to get the sum of specific values ​​instead of deductions when creating stacked histograms. You must specify the x , fill= and weight=amount values ​​so that the sum of the amount values ​​is used to create the bar heights. It also automatically ensures that fill= values ​​are in the same order.

 ggplot(dat,aes(month,fill=family,weight=amount))+geom_bar() 

enter image description here

+4
source

Source: https://habr.com/ru/post/943563/


All Articles