ruby-on-railschartkick

Multiple Series Line Chart Using Chartkick and Rails


I'm trying to setup a multiple series line chart that shows monthly total exams by modality.

Something similar to this chart:

enter image description here

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:

enter image description here

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.


Solution

  • 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:

    enter image description here