简体   繁体   English

如何使用Chartkick对列进行分组

[英]How can I group columns with Chartkick

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. 我想显示按年份分组的Chartkick柱形图 I tried the following plan call in my Rails view: 我在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所获得的

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所需格式的格式生成数据可能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM