Search code examples
ruby-on-railsarraysrubychartkick

Need guidance to use .map,.group,.pluck, etc. to make multi series line chart in ruby on rails app


I'm trying to display a multi series line chart using chartkick in a Ruby on Rails app.

The chart should display paper_types and the weightfor each type during some time period.

SCREENSHOT ADDED

enter image description here

This is my latest try:

<%= line_chart [                            
  {name: @pappi.map{|p| [p.paper_type]}, data: @pappi.map{|t| [t.date, t.paper_weight] }, 'interpolateNulls':true}
 ] %>

Where @pappi = Paper.all

The code above outputs as the picture below, where every paper_type rounds up on one single line, instead of showing separate lines for each paper_type. enter image description here

What I'm looking for is a chart similar to the screenshot below, were each paper_type has it's own line.

enter image description here

Can someone please help me with this so I can get the outcome I want?


Solution

  • I did not test this, only read the doc and concluded the following:

    line_chart expects you to give argument structured like this: (from the Javascript documentation)

    line_chart [
      { name: 'Line1', data: { '2017-01-01' => 2, '2017-01-08' => 3 } },
      { name: 'Line2', data: { '2017-01-01' => 1, '2017-01-08' => 7 } },
    ]
    # try it in your view to make sure it works as described below
    

    This will create a chart with 2 lines (Line1 and Line2), horizontal axis will contain 2 values 2017-01-01 and 2017-01-08 and the vertical axis will be a scale, probably from 1 to 7 (min from data to max from data).


    Following this data structure in your context:

    Specs (correct me if I am wrong):

    • one line for each different paper_type
    • weight value for a given paper_type and a given date

    Object mapping to match the desired data structure:

    # controller
    all_paper_type_values = Paper.all.pluck(:paper_type).uniq
    @data_for_chart = all_paper_type_values.map do |paper_type|
      { name: paper_type, data: Paper.where(paper_type: paper_type).group_by_month(:created_at).sum(:weight) }
    end
    
    # view
    <%= line_chart(@data_for_chart) %>
    

    This is no scoped to any user / dates (period). You will have to include this in the code above.

    Try this and let me know if it fails.