Class: RailsDataExplorer::Chart::StackedHistogramTemporal

Inherits:
RailsDataExplorer::Chart show all
Defined in:
lib/rails_data_explorer/chart/stacked_histogram_temporal.rb

Overview

Responsibilities:

* Render a stacked bar chart for bivariate analysis of a temporal and a
  categorical data series.

Collaborators:

* DataSet

Instance Attribute Summary

Attributes inherited from RailsDataExplorer::Chart

#output_buffer

Instance Method Summary collapse

Methods inherited from RailsDataExplorer::Chart

#dom_id, #render?

Constructor Details

#initialize(_data_set, options = {}) ⇒ StackedHistogramTemporal

Returns a new instance of StackedHistogramTemporal.



15
16
17
18
# File 'lib/rails_data_explorer/chart/stacked_histogram_temporal.rb', line 15

def initialize(_data_set, options = {})
  @data_set = _data_set
  @options = {}.merge(options)
end

Instance Method Details

#compute_chart_attrsObject



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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/rails_data_explorer/chart/stacked_histogram_temporal.rb', line 20

def compute_chart_attrs
  x_candidates = @data_set.data_series.find_all { |ds|
    (ds.chart_roles[Chart::StackedHistogramTemporal] & [:x, :any]).any?
  }.sort { |a,b| b.uniq_vals.length <=> a.uniq_vals.length }
  y_candidates = @data_set.data_series.find_all { |ds|
    (ds.chart_roles[Chart::StackedHistogramTemporal] & [:y, :any]).any?
  }

  x_ds = x_candidates.first
  y_ds = (y_candidates - [x_ds]).first
  return false  if x_ds.nil? || y_ds.nil?

  # initialize data_matrix
  data_matrix = { _sum: { _sum: 0 } }
  x_ds.uniq_vals.each { |x_val|
    data_matrix[x_val] = {}
    data_matrix[x_val][:_sum] = 0
    y_ds.uniq_vals.each { |y_val|
      data_matrix[x_val][y_val] = 0
      data_matrix[:_sum][y_val] = 0
    }
  }
  # populate data_matrix
  x_ds.values.length.times { |idx|
    x_val = x_ds.values[idx]
    y_val = y_ds.values[idx]
    data_matrix[x_val][y_val] += 1
    data_matrix[:_sum][y_val] += 1
    data_matrix[x_val][:_sum] += 1
    data_matrix[:_sum][:_sum] += 1
  }

  x_sorted_keys = x_ds.uniq_vals.sort(
    &x_ds.label_sorter(
      nil,
      lambda { |a,b| data_matrix[b][:_sum] <=> data_matrix[a][:_sum] }
    )
  )
  y_sorted_keys = y_ds.uniq_vals.sort(
    &y_ds.label_sorter(
      nil,
      lambda { |a,b| data_matrix[:_sum][b] <=> data_matrix[:_sum][a] }
    )
  )

  values = case @data_set.dimensions_count
  when 2
    y_sorted_keys.map { |y_val|
      x_sorted_keys.map { |x_val|
        {
          x: x_val,
          y: data_matrix[x_val][y_val],
          c: y_val
        }
      }
    }.flatten
  else
    raise(ArgumentError.new("Exactly two data series required for contingency table."))
  end
  {
    values: values,
    x_axis_label: x_ds.name,
    x_axis_tick_format: 'function(d) { return d }',
    y_axis_label: "#{ y_ds.name } distribution [%]",
    y_axis_tick_format: "d3.format('.1%')",
  }
end

#renderObject



88
89
90
91
92
93
# File 'lib/rails_data_explorer/chart/stacked_histogram_temporal.rb', line 88

def render
  return ''  unless render?
  ca = compute_chart_attrs
  return ''  unless ca
  render_vega(ca)
end

#render_vega(ca) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/rails_data_explorer/chart/stacked_histogram_temporal.rb', line 95

def render_vega(ca)
  %(
    <div class="rde-chart rde-stacked-histogram-temporal">
      <h3 class="rde-chart-title">Stacked Histogram (temporal)</h3>
      <div id="#{ dom_id }"></div>
      <script type="text/javascript">
        (function() {
          var spec = {
            "width": 960,
            "height": 200,
            "padding": {"top": 10, "left": 50, "bottom": 50, "right": 100},
            "data": [
              {
                "name": "table",
                "values": #{ ca[:values].to_json }
              },
              {
                "name": "stats",
                "source": "table",
                "transform": [
                  {"type": "facet", "keys": ["data.x"]},
                  {"type": "stats", "value": "data.y"}
                ]
              }
            ],
            "scales": [
              {
                "name": "x",
                "type": "ordinal",
                "range": "width",
                "domain": {"data": "table", "field": "data.x"}
              },
              {
                "name": "y",
                "type": "linear",
                "range": "height",
                "nice": true,
                "domain": {"data": "stats", "field": "sum"}
              },
              {
                "name": "color",
                "type": "ordinal",
                "range": "category10"
              }
            ],
            "axes": [
              {
                "type": "x",
                "scale": "x",
                "title": "#{ ca[:x_axis_label] }",
                "format": #{ ca[:x_axis_tick_format] },
              },
              {
                "type": "y",
                "scale": "y",
                "title": "#{ ca[:y_axis_label] }",
                "format": #{ ca[:y_axis_tick_format] },
              }
            ],
            "marks": [
              {
                "type": "group",
                "from": {
                  "data": "table",
                  "transform": [
                    {"type": "facet", "keys": ["data.c"]},
                    {"type": "stack", "point": "data.x", "height": "data.y"}
                  ]
                },
                "marks": [
                  {
                    "type": "rect",
                    "properties": {
                      "enter": {
                        "x": {"scale": "x", "field": "data.x"},
                        "width": {"scale": "x", "band": true, "offset": -1},
                        "y": {"scale": "y", "field": "y"},
                        "y2": {"scale": "y", "field": "y2"},
                        "fill": {"scale": "color", "field": "data.c"}
                      },
                    }
                  }
                ]
              }
            ],
            "legends": [
              {
                "fill": "color",
              }
            ],
          };

          vg.parse.spec(spec, function(chart) {
            var view = chart({ el:"##{ dom_id }" }).update();
          });

        })();
      </script>
    </div>
  )
end