操作rChart的哈希数据 - Ruby

时间:2013-05-15 14:12:12

标签: ruby arrays hash

我有一些代码可以包含CSV文件。我正在尝试使用此信息在Ruby中使用rChart创建图表。

在我的代码中,我将CSV文件加载到如下所示的哈希:

CSV.new(open(url),:headers => true, :header_converters => :symbol, :converters => :all).each do |line|
    title = line.headers[0]
    points[line.fields[0]] = Hash[line.headers[1..-1].zip(line.fields[1..-1])]
end

...后来

points.keys.sort.each do |key|
    puts "---" # added for clarification in SO example of each key 
    points[key].each {|serie_name, point| puts "#{serie_name} = #{point}"}
    puts points[key].length # total number of series
end

输出:

---
wmt_oracle = 68
irt_oracle = 44
wmt_sql = 20
irt_sql = 11
operations = 4
5
---
wmt_oracle = 23
irt_oracle = 44
wmt_sql = 160
irt_sql = 8
operations = 3
5
---
wmt_oracle = 66
irt_oracle = 224
wmt_sql = 48
irt_sql = 15
operations = 3
5

在rChart中,堆叠条形图的数据点以下列方式添加:

data.add_point([9,9,9,10,10,11,12,14,16,17,18,18,19,19,18,15,12,10,9],"Serie1");
data.add_point([10,11,11,12,12,13,14,15,17,19,22,24,23,23,22,20,18,16,14],"Serie2");
data.add_point([4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22],"Serie3");
. . .

对于上述数据,我需要让我的数据如下所示:

data.add_point([68,23,66],"wmt_oracle");
data.add_point([44,44,224], "irt_oracle")
data.add_point([20,160,48], "wmt_sql")
data.add_point([11,8,15], "irt_sql")
data.add_point([4,3,3], "operations")

格式为data.add_point(array_of_points, serie_name)

如何将哈希数据从这种格式中获取?

1 个答案:

答案 0 :(得分:1)

我认为这就是你要找的东西:

# Hash with default value []
transformed = Hash.new { |hash,key| hash[key] = [] } 
points.each { |k,v| v.each { |name,count| transformed[name] << count } }

现在transformed将为{"wmt_oracle" => [68,23,66], "irt_oracle" => [44,44,224], ...}

然后添加点数:

transformed.each { |name, values| data.add_point(values, name) }