Multiple series using pluck and chartkick?

104 Views Asked by At

I have some data in a table that looks like the following:

date      apples      pears      oranges
1         3           2          0
2         1           5          0
3         0           2          1
4         0           0          1
5         0           1          1

I can plot the count of a fruit by date using:

<%= line_chart FruitCount.pluck(:date, :apples), xtitle: "Date", ytitle: "Count" %>

I can't workout how to plot apples, pears and oranges onto the same plot. I thought it might be something like the following:

<%= line_chart [
                 { name: Apples, data: FruitCount.pluck(:date, :apples) },
                 { name: Pears, data: FruitCount.pluck(:date, :pears) }
                 { name: Oranges, data: FruitCount.pluck(:date, :oranges) }
               ], xtitle: "Date", ytitle: "Count" %>

All help greatly appreciated.

Edit:

The issue was a missed comma and the names not being strings. The code below works:

<%= line_chart [
                 { name: "Apples", data: FruitCount.pluck(:date, :apples) },
                 { name: "Pears", data: FruitCount.pluck(:date, :pears) },
                 { name: "Oranges", data: FruitCount.pluck(:date, :oranges) },
               ], xtitle: "Date", ytitle: "Count"  %>
1

There are 1 best solutions below

0
Beartech On

line chart

I have a line chart showing items that are "expiring" on a given date grouped by month using line_chart. I like the built-in feature of clicking on the color keys to show/hide each line. I use a complicated query to get info in this format:

{["Footwear", Sat, 01 May 2021]=>0,
 ["Footwear", Tue, 01 Jun 2021]=>1,
 ["Footwear", Thu, 01 Jul 2021]=>0,
  ...
 ["Coat", Sun, 01 Aug 2021]=>0,
 ["Coat", Wed, 01 Sep 2021]=>0,
 ["Coat", Fri, 01 Oct 2021]=>0,
 ["Coat", Mon, 01 Nov 2021]=>0,
  ...
 ["Helmet", Wed, 01 Dec 2021]=>0,
 ["Helmet", Sat, 01 Jan 2022]=>0,
 ["Helmet", Tue, 01 Feb 2022]=>1,
 ["Helmet", Tue, 01 Mar 2022]=>2,
 ["Helmet", Fri, 01 Apr 2022]=>0...}

So just hand line_chart a hash with data like: ["Apple", <date>] => count] and chartkick will do the rest. I have a very limited view of your table structures but going on what you have given us I think you could do:

hash_for_chart = {}

FruitCount.pluck(:date, :apples, :pears, :oranges).each do |arr| 
  hash_for_chart['Apples', arr[0]] = arr[1] 
  hash_for_chart['Pears', arr[0]] = arr[2]  
  hash_for_chart['Oranges', arr[0]] = arr[3] 
end

Here we are grabbing every FruitCount record, plucking the date and the three counts so we have an array of those values. Then we add a hash pair for each of the three values on that date to a hash that we will pass to line_chart

line_chart hash_for_chart

There may be a more complex AR query that could give you the same data but hard for me to say with such limited info about your DB.