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?
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)
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With