Debian Codegraph @

js/src/BarsModel.ts

raw
1 /* Copyright 2015 Bloomberg Finance L.P.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 import * as d3 from 'd3';
17 import * as _ from 'underscore';
18 import { MarkModel } from './MarkModel';
19 import * as serialize from './serialize';
20
21 export interface BarGroupValue {
22 index: number;
23 subIndex: number;
24 y0: number;
25 y1: number;
26 yRef: number;
27 x: number;
28 y: number;
29 colorIndex: number;
30 opacityIndex: number;
31 color: string;
32 }
33
34 export interface BarData {
35 key: number;
36 values: BarGroupValue[];
37 posMax: number;
38 negMax: number;
39 }
40
41 export class BarsModel extends MarkModel {
42 defaults() {
43 return {
44 ...MarkModel.prototype.defaults(),
45 _model_name: 'BarsModel',
46 _view_name: 'Bars',
47 x: [],
48 y: [],
49 color: null,
50 scales_metadata: {
51 x: { orientation: 'horizontal', dimension: 'x' },
52 y: { orientation: 'vertical', dimension: 'y' },
53 color: { dimension: 'color' },
54 },
55 color_mode: 'auto',
56 opacity_mode: 'auto',
57 type: 'stacked',
58 colors: ['steelblue'],
59 padding: 0.05,
60 fill: true,
61 stroke: null,
62 stroke_width: 1,
63 base: 0.0,
64 opacities: [],
65 orientation: 'vertical',
66 align: 'center',
67 label_display: false,
68 label_display_format: '.2f',
69 label_display_font_style: {},
70 label_display_horizontal_offset: 0.0,
71 label_display_vertical_offset: 0.0,
72 };
73 }
74
75 initialize(attributes, options) {
76 super.initialize(attributes, options);
77 this.yIs2d = false;
78 this.on_some_change(['x', 'y', 'base'], this.update_data, this);
79 this.on_some_change(
80 ['color', 'opacities', 'color_mode', 'opacity_mode'],
81 function () {
82 this.update_color();
83 this.trigger('colors_updated');
84 },
85 this
86 );
87 // FIXME: replace this with on("change:preserve_domain"). It is not done here because
88 // on_some_change depends on the GLOBAL backbone on("change") handler which
89 // is called AFTER the specific handlers on("change:foobar") and we make this
90 // assumption.
91 this.on_some_change(['preserve_domain'], this.update_domains, this);
92 this.update_data();
93 this.update_color();
94 this.update_domains();
95 }
96
97 update_data() {
98 let x_data = this.get('x');
99 let y_data = this.get('y');
100 y_data = y_data.length === 0 || !_.isNumber(y_data[0]) ? y_data : [y_data];
101
102 this.baseValue = this.get('base');
103 if (this.baseValue === undefined || this.baseValue === null) {
104 this.baseValue = 0;
105 }
106
107 if (x_data.length === 0 || y_data.length === 0) {
108 this.mark_data = [];
109 this.yIs2d = false;
110 } else {
111 x_data = x_data.slice(0, d3.min(y_data.map((d) => d.length)));
112
113 // since x_data may be a TypedArray, explicitly use Array.map
114 this.mark_data = Array.prototype.map.call(x_data, (x_elem, index) => {
115 const data: any = {};
116 let y0 = this.baseValue;
117 let y0_neg = this.baseValue;
118 let y0_left = this.baseValue;
119 data.key = x_elem;
120
121 // since y_data may be a TypedArray, explicitly use Array.map
122 data.values = Array.prototype.map.call(y_data, (y_elem, y_index) => {
123 let value = y_elem[index] - this.baseValue;
124 if (isNaN(value)) {
125 value = 0;
126 }
127 const positive = value >= 0;
128 return {
129 index: index,
130 subIndex: y_index,
131 x: x_elem,
132 // In the following code, the values y0, y1 are
133 // only relevant for a stacked bar chart. grouped
134 // bars only deal with baseValue and y.
135
136 // y0 is the value on the y scale for the upper end
137 // of the bar.
138 y0: positive
139 ? y0
140 : (function () {
141 y0_left += value;
142 return y0_left;
143 })(),
144 // y1 is the value on the y scale for the lower end
145 // of the bar.
146 y1: positive
147 ? (y0 += value)
148 : (function () {
149 y0_neg += value;
150 return y0_neg - value;
151 })(),
152 // yRef is the value on the y scale which represents
153 // the height of the bar
154 yRef: value,
155 y: y_elem[index],
156 };
157 });
158
159 // posMax is the maximum positive value for a group of
160 // bars.
161 data.posMax = y0;
162 // negMax is the minimum negative value for a group of
163 // bars.
164 data.negMax = y0_neg;
165 return data;
166 });
167 this.yIs2d = this.mark_data[0].values.length > 1;
168 this.update_color();
169 }
170 this.update_domains();
171 this.trigger('data_updated');
172 }
173
174 get_data_dict(data, index) {
175 return data;
176 }
177
178 update_color() {
179 //Function to update the color attribute for the data. In scatter,
180 //this is taken care of by the update_data itself. This is separate
181 //in bars because update data does a lot more complex calculations
182 //which should be avoided when possible
183 if (!this.mark_data) {
184 return;
185 }
186 const color = this.get('color') || [];
187 const color_scale = this.get('scales').color;
188 const color_mode = this.get('color_mode');
189 const apply_color_to_groups =
190 color_mode === 'group' || (color_mode === 'auto' && !this.yIs2d);
191 const apply_color_to_group_element =
192 color_mode === 'element' || (color_mode === 'auto' && this.yIs2d);
193
194 const opacity_mode = this.get('opacity_mode');
195 const apply_opacity_to_groups =
196 opacity_mode === 'group' || (opacity_mode === 'auto' && !this.yIs2d);
197 const apply_opacity_to_group_element =
198 opacity_mode === 'element' || (opacity_mode === 'auto' && this.yIs2d);
199
200 let element_idx = 0;
201 this.mark_data.forEach((single_bar_d, bar_grp_index) => {
202 single_bar_d.values.forEach((bar_d, bar_index) => {
203 bar_d.colorIndex = apply_color_to_groups
204 ? bar_grp_index
205 : apply_color_to_group_element
206 ? bar_index
207 : element_idx;
208 bar_d.opacityIndex = apply_opacity_to_groups
209 ? bar_grp_index
210 : apply_opacity_to_group_element
211 ? bar_index
212 : element_idx;
213 bar_d.color = color[bar_d.colorIndex];
214
215 element_idx++;
216 });
217 });
218
219 if (color_scale && color.length > 0) {
220 if (!this.get('preserve_domain').color) {
221 color_scale.compute_and_set_domain(color, this.model_id + '_color');
222 } else {
223 color_scale.del_domain([], this.model_id + '_color');
224 }
225 }
226 }
227
228 update_domains() {
229 if (!this.mark_data) {
230 return;
231 }
232 const scales = this.get('scales');
233 const dom_scale = scales.x;
234 const range_scale = scales.y;
235
236 if (!this.get('preserve_domain').x) {
237 dom_scale.compute_and_set_domain(
238 this.mark_data.map((elem) => {
239 return elem.key;
240 }),
241 this.model_id + '_x'
242 );
243 } else {
244 dom_scale.del_domain([], this.model_id + '_x');
245 }
246
247 if (!this.get('preserve_domain').y) {
248 if (this.get('type') === 'stacked') {
249 range_scale.compute_and_set_domain(
250 [
251 d3.min(this.mark_data, (c: any) => {
252 return c.negMax;
253 }),
254 d3.max(this.mark_data, (c: any) => {
255 return c.posMax;
256 }),
257 this.baseValue,
258 ],
259 this.model_id + '_y'
260 );
261 } else {
262 const min = d3.min(this.mark_data, (c: any) => {
263 return d3.min(c.values, (val: any) => {
264 return val.yRef;
265 });
266 });
267 const max = d3.max(this.mark_data, (c: any) => {
268 return d3.max(c.values, (val: any) => {
269 return val.yRef;
270 });
271 });
272 range_scale.compute_and_set_domain(
273 [min, max, this.baseValue],
274 this.model_id + '_y'
275 );
276 }
277 } else {
278 range_scale.del_domain([], this.model_id + '_y');
279 }
280 }
281
282 static serializers = {
283 ...MarkModel.serializers,
284 x: serialize.array_or_json_serializer,
285 y: serialize.array_or_json_serializer,
286 color: serialize.array_or_json_serializer,
287 };
288
289 yIs2d: boolean;
290 baseValue: number;
291 mark_data: BarData[];
292 }