Debian Codegraph @

bqplot/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 x: number;
27 y: number;
28 colorIndex: number;
29 opacityIndex: number;
30 color: string;
31 }
32
33 export interface BarData {
34 key: number;
35 values: BarGroupValue[];
36 posMax: number;
37 negMax: number;
38 }
39
40 export class BarsModel extends MarkModel {
41 defaults() {
42 return {
43 ...MarkModel.prototype.defaults(),
44 _model_name: 'BarsModel',
45 _view_name: 'Bars',
46 x: [],
47 y: [],
48 color: null,
49 scales_metadata: {
50 x: { orientation: 'horizontal', dimension: 'x' },
51 y: { orientation: 'vertical', dimension: 'y' },
52 color: { dimension: 'color' },
53 },
54 color_mode: 'auto',
55 opacity_mode: 'auto',
56 type: 'stacked',
57 colors: ['steelblue'],
58 padding: 0.05,
59 fill: true,
60 stroke: null,
61 stroke_width: 1,
62 base: 0.0,
63 opacities: [],
64 orientation: 'vertical',
65 align: 'center',
66 label_display: false,
67 label_display_format: '.2f',
68 label_display_font_style: {},
69 label_display_horizontal_offset: 0.0,
70 label_display_vertical_offset: 0.0,
71 };
72 }
73
74 initialize(attributes, options) {
75 super.initialize(attributes, options);
76 this.yIs2d = false;
77 this.on_some_change(['x', 'y', 'base'], this.update_data, this);
78 this.on_some_change(
79 ['color', 'opacities', 'color_mode', 'opacity_mode'],
80 function () {
81 this.update_color();
82 this.trigger('colors_updated');
83 },
84 this
85 );
86 // FIXME: replace this with on("change:preserve_domain"). It is not done here because
87 // on_some_change depends on the GLOBAL backbone on("change") handler which
88 // is called AFTER the specific handlers on("change:foobar") and we make this
89 // assumption.
90 this.on_some_change(['preserve_domain'], this.update_domains, this);
91 this.update_data();
92 this.update_color();
93 this.update_domains();
94 }
95
96 update_data() {
97 let x_data = this.get('x');
98 let y_data = this.get('y');
99 y_data = y_data.length === 0 || !_.isNumber(y_data[0]) ? y_data : [y_data];
100
101 this.baseValue = this.get('base');
102 if (this.baseValue === undefined || this.baseValue === null) {
103 this.baseValue = 0;
104 }
105
106 if (x_data.length === 0 || y_data.length === 0) {
107 this.mark_data = [];
108 this.yIs2d = false;
109 } else {
110 x_data = x_data.slice(0, d3.min(y_data.map((d) => d.length)));
111
112 // since x_data may be a TypedArray, explicitly use Array.map
113 this.mark_data = Array.prototype.map.call(x_data, (x_elem, index) => {
114 const data: any = {};
115 data.key = x_elem;
116
117 // split bins into positive ( value > baseValue) and negative, and stack those separately
118 // accumulates size/height of histogram values for stacked histograms
119 let cumulativePos = this.baseValue;
120 let cumulativeNeg = this.baseValue;
121
122 // since y_data may be a TypedArray, explicitly use Array.map
123 data.values = Array.prototype.map.call(y_data, (y_elem, y_index) => {
124 // y0, y1 are the upper and lower bound of the bars and
125 // only relevant for a stacked bar chart. grouped
126 // bars only deal with baseValue and y.
127
128 let y0, y1;
129 const value = isNaN(y_elem[index])
130 ? 0
131 : y_elem[index] - this.baseValue;
132
133 if (value >= 0) {
134 y0 = cumulativePos;
135 if (!isNaN(y_elem[index])) {
136 cumulativePos += value;
137 }
138 y1 = cumulativePos;
139 } else {
140 // reverse y1 and y0 to not have negative heights
141 y1 = cumulativeNeg;
142 if (!isNaN(y_elem[index])) {
143 cumulativeNeg += value;
144 }
145 y0 = cumulativeNeg;
146 }
147
148 return {
149 index: index,
150 subIndex: y_index,
151 x: x_elem,
152 y0,
153 y1,
154 y: y_elem[index],
155 };
156 });
157
158 let extremes = [this.baseValue, cumulativeNeg, cumulativePos];
159 // posMax is the maximum positive value for a group of
160 // bars.
161 data.posMax = d3.max(extremes);
162 // negMax is the minimum negative value for a group of
163 // bars.
164 data.negMax = d3.min(extremes);
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 }