Class: Tiler::Widgets::PieChartQuery
- Inherits:
-
Query::Base
- Object
- Query::Base
- Tiler::Widgets::PieChartQuery
- Defined in:
- lib/tiler/widgets/pie_chart.rb
Constant Summary collapse
- DEFAULT_LIMIT =
6- OTHER_LABEL =
"Other".freeze
Constants inherited from Query::Base
Instance Attribute Summary
Attributes inherited from Query::Base
Instance Method Summary collapse
Methods inherited from Query::Base
Constructor Details
This class inherits a constructor from Tiler::Query::Base
Instance Method Details
#call ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/tiler/widgets/pie_chart.rb', line 10 def call group_col = config["group_column"] agg = config["aggregation"] || "count" val_col = config["value_column"] limit = (config["limit"] || DEFAULT_LIMIT).to_i.clamp(1, 50) return empty_result if group_col.blank? # Aggregate every group, then sort descending by value so the largest # slices win the visible spots. Anything past `limit` collapses into a # single "Other" slice (only when there's actually overflow). groups = distinct_values(group_col) all_pairs = groups.map { |g| [ g, aggregate_for_group(group_col, g, val_col, agg).to_f ] } .sort_by { |(_, v)| -v } kept = all_pairs.first(limit) leftover = all_pairs.drop(limit) labels = kept.map(&:first) data = kept.map(&:last) if leftover.any? other_value = leftover.sum { |(_, v)| v } if other_value > 0 labels << OTHER_LABEL data << other_value end end colors = labels.each_index.map { |i| chart_colors[i % chart_colors.size] } # Legend on the right at panel widths >= 4 cols (catalog spec); top # otherwise so the slices keep room to breathe in narrow tiles. legend_pos = panel.width.to_i >= 4 ? "right" : "top" { labels: labels, datasets: [ { data: data, backgroundColor: colors.map { |c| "#{c}cc" }, borderColor: colors, borderWidth: 2 } ], options: { plugins: { legend: { position: legend_pos } } } } end |