Chartkick gem,限制饼图和多个系列中的组

Chartkick gem, limit group in pie chart and multiple series

我对分组记录有一些小问题。图表代码:

<%= pie_chart CountChatLine.group(:channel).count %>

问题是,我的数据库中有很多 :channels,图表如下所示:

我能以某种方式只取 N top :channels 并将其余部分相加为 others 或其他吗?或者每 :channel 个小于 N% 的都添加到其他人?

chartkick gem(我刚开始使用它)将绘制您提供的任何数据。至于您提供的数据是什么样子,完全取决于您。

是的,您绝对可以通过聚合它们来减少饼图中的切片数量,但是,您需要自己这样做。

您可以在您的模型中编写一个方法来总结这一点,并这样调用:

<%= pie_chart CountChatLine.summarized_channel_info %>

CountChatLine 模型中的方法:

def self.summarized_channel_info
   {code to get info and convert it into format you really want}
end

希望对您有所帮助。我就是这么做的。

一些沉重的思考和@Agazoom 的帮助,我已经做到了。 代码:

  @top_count = 5
  @size = CountChatLine.group(:channel).count.count-@top_count 
  @data_top = CountChatLine.group(:channel).order("count_all").reverse_order.limit(@top_count).count 
  @data_other = CountChatLine.group(:channel).order("count_all").limit(@size).count 
  @data_other_final = {"others" => 0} 
  @data_other.each { |name, count| @data_other_final = {"others" => @data_other_final["others"]+count }} 
  @sum_all_data = @data_top.reverse_merge!(@data_other_final)

IDK如果有更好的方法。如果有,请post它。但就目前而言,它有效:)

如果我们可以让 DB 完成工作并且 return 最好的结果,那就太好了,但是这样的事情应该可行:

<%= pie_chart CountChatLine.group(:channel).count.sort_by {|k,v| v}.reverse[0..4] %>

[0..4] 将显示前 5 个最大的结果。 [0..9] 将是前 10 名。

正在return从数据库中获取结果 然后按值(从低到高)对它们进行排序 然后反转排序(从高到低) 然后只取前 [0..4] 个结果。