Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Using groupdate & chartkick to create a cumulative user graph

I'm using groupdate and chartkick to try and display a graph showing the growth (and fall) of our user base over time.

Using the following it works fine in a column chart, but goes haywire in a line chart:

sum=0
User.group_by_day(:created_at).count.map { |x,y| { x => (sum += y)} }.reduce({}, :merge)

Can anyone point me in the right direction? Or is there a better way to get this working?

like image 305
Les Avatar asked May 23 '13 17:05

Les


2 Answers

It's because you need to sort before you do the cumulative sum.

Try this:

sum=0
User.group_by_day(:created_at).count.to_a.sort{|x,y| x[0] <=> y[0]}.map { |x,y| { x => (sum += y)} }.reduce({}, :merge)
like image 88
Martin May Avatar answered Nov 04 '22 09:11

Martin May


Martin's answer was close, but I ended up using:

User.group_by_week(:created_at).order("week asc").count.map { |x,y| { x => (sum += y)} }.reduce({}, :merge)

To get weekly - notice the order("week asc") - it's what fixed it...

like image 12
Les Avatar answered Nov 04 '22 10:11

Les