0

I have the following data structure:

@data = [['Year', 'Sales', 'Expenses', 'Profit'],
          ['2014', 1000, 400, 200],
          ['2015', 1170, 460, 250],
          ['2016', 660, 1120, 300],
          ['2017', 1030, 540, 350]]

and I want to display a column chart with Chartkick grouped by Year. I tried the following plan call in my Rails view:

<%= column_chart @data %>

but it show an empty chart. What's the way to group set of data?

This is what I get using plan Google Chart APIs.

bcesars
  • 1,016
  • 1
  • 17
  • 36
Luca G. Soave
  • 12,271
  • 12
  • 58
  • 109

1 Answers1

3

I think you want your data structure to look like:

[
  {
    name: "Sales", 
    data: [
      ["2014", 1000], ["2015", 1170], ["2016", 660], ["2017", 1030]
    ]
  }, # ...
] 

Probably the easiest way to do this with your current data structure would be like:

 data = [['Year', 'Sales', 'Expenses', 'Profit'],
   ['2014', 1000, 400, 200],
   ['2015', 1170, 460, 250],
   ['2016', 660, 1120, 300],
   ['2017', 1030, 540, 350]]

@data = (1..3).map do |i|
  {
    name: data.first[i],
    data: data[1..-1].map { |x| [ x[0], x[i] ] }
  }
end

But it would probably be better to generate your data in a format closer to what chartkick wants.

Jacob Brown
  • 7,221
  • 4
  • 30
  • 50
  • @Luca I'm confused; did you try my code? It looks like http://imgur.com/4DITxU0, which is pretty much just the same as your Google Charts example. – Jacob Brown Jan 26 '15 at 21:49
  • yes it works fine. Thanks also for the suggestion to get better data from the beginning, I'll try to refine the process :-) – Luca G. Soave Jan 26 '15 at 22:03