Reputation: 185
I'm trying to setup a multiple series line chart that shows monthly total exams by modality.
Something similar to this chart:
I want the modalities to be colored: (CT, MR, US, XR, MG, BD, NM)
The monthly date (to_date) will be the X-Axis data label.
Exams model:
has_many :modalities
Modality model:
belongs_to :exam
I have a monthly_modalities action on my Charts controller:
def monthly_modalities
chart_data = Modality.joins(:exam).map {|m|
{name: m.name, data: m.exam.to_date}
}
render json: chart_data.each do |e|
{name: :name, data: e.group_by_month(:to_date, format: '%b', range: 1.year).sum(:total).chart_json}
end
end
Here's the chart that is created:
The problem is that repeating modalities aren't grouping together and the monthly date (to_date) isn't showing on the X-Axis data label.
Upvotes: 2
Views: 4953
Reputation: 185
I ended up asking another question regarding this issue but even more specific about how I was looping through and outputting the data.
Here's the way I solved this:
now = Time.now
chart_data = Modality.joins(:exam)
.where(exams: {from_date: (now - 1.year)..now}).map {|m|
{name: m.name, data: {m.exam.from_date => m.total}}}
@exams = chart_data.group_by {|h| h[:name]}
.map {|k, v| {name: k, data: v.map {|h| h[:data]}.reduce(&:merge)}}
Here's the hash needed for displaying the chart:
[
{:name=>"MR", :data=>{Wed, 01 Feb 2017=>41, Wed, 01 Mar 2017=>66, Sat, 01 Apr 2017=>73, Sun, 01 Jan 2017=>44}},
{:name=>"CT", :data=>{Wed, 01 Feb 2017=>4, Wed, 01 Mar 2017=>6, Sat, 01 Apr 2017=>8, Sun, 01 Jan 2017=>52}},
{:name=>"XR", :data=>{Wed, 01 Mar 2017=>1}},
{:name=>"US", :data=>{Sat, 01 Apr 2017=>1, Sun, 01 Jan 2017=>1}}
]
In my view, I rendered the chart like so:
<%= line_chart @exams %>
And the correct chart:
Upvotes: 8
Reputation: 53
I don't know if your still looking for the answer but I just figured out today how to do it. I had a similar issues but you have to play with the code a little bit to make it work for you. Here is the LINK. I hope it will help you but for me it works well.
I will give a shot with your datas, try and tell me if it works, paste this in your corresponding view :
<%= column_chart Modality.joins(:exam).group('exams.name').group_by_month(:to_date, format: '%b', range: 1.year).sum(:total) %>
Upvotes: 1