如何使用Chartkick对列进行分组

时间:2021-01-29 22:30:28

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:

并且我想显示Chartkick按年份分组的柱形图。我在Rails视图中尝试了以下计划调用:

<%= 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.

这就是我使用Google Chart API的计划。

1 个解决方案

#1


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.

但是,以更接近chartkick想要的格式生成数据可能会更好。

#1


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.

但是,以更接近chartkick想要的格式生成数据可能会更好。