-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpx-simple-horizontal-bar-chart.html
601 lines (539 loc) · 20.5 KB
/
px-simple-horizontal-bar-chart.html
1
2
3
4
5
6
7
8
9
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
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
87
88
89
90
91
92
93
94
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
<!--
Copyright (c) 2018, General Electric
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<link rel="import" href="../polymer/polymer.html"/>
<link rel="import" href="../px-simple-chart-common-behavior/px-simple-chart-common-behavior.html"/>
<link rel="import" href="../px-simple-chart-common-behavior/px-simple-chart-common-behavior-colors.html" />
<link rel="import" href="css/px-simple-horizontal-bar-chart-styles.html"/>
<script type="text/javascript" src="../es6-promise/es6-promise.min.js"></script>
<script type="text/javascript" src="../d3/d3.js"></script>
<!--
### Usage
<px-simple-horizontal-bar-chart chart-data="[1,2,3]"></px-simple-horizontal-bar-chart>
### Styling
The following custom properties are available for styling.
Custom property | Description
:----------------|:-------------
`--px-simple-horizontal-bar-chart-background-color` | The background color of the chart
`--px-simple-horizontal-bar-chart-legend-text-color` | The legend text color
`--px-simple-horizontal-bar-chart-label-text-color` | The label text color
`--px-simple-horizontal-bar-chart-axis-color` | The color of the horizontal axis
`--px-vis-series-color-[n]` | A series of color values to loop through when coloring the chart (see below)
### Styling series colors
If you want to set custom chart colors, it's recommended to use CSS custom properties. You can set as many colors as you want using the `--px-vis-series-color-[n]` variable pattern, where `n` starts at 0 and increases by 1 with each new color. For example:
<style>
:root {
--px-vis-series-color-0: #aaa;
--px-vis-series-color-1: #bbb;
--px-vis-series-color-2: #ccc;
--px-vis-series-color-3: #ddd;
...
};
</style>
<px-simple-horizontal-bar-chart chart-data="[1,2,3]" ...>
</px-simple-horizontal-bar-chart>
A few things to note:
<ul>
<li>If you provide more data series than available series colors, the element will loop through available colors starting at the beginning.</li>
<li>If you do not specify any style variables, a default series of data visualization colors will be applied.</li>
<li>If you set the `colors` attribute, your style variables will be overriden and ignored.</li>
<li>There cannot be gaps in the sequential numbers you provide. Evaluation of the colors will end at the last sequential number. (See example below.)</li>
</ul>
The following theme would be incorrect because it has a gap. All series in your chart would be colored red:
<style>
:root {
--px-vis-series-color-0: red;
/* skips --px-vis-series-color-1 */
--px-vis-series-color-2: blue;
--px-vis-series-color-3: orange;
...
};
</style>
<px-simple-horizontal-bar-chart chart-data="[1,2,3]" ...>
</px-simple-horizontal-bar-chart>
@element px-simple-horizontal-bar-chart
@blurb Predix UI Simple Horizontal Bar Chart
@homepage index.html
@demo index.html
-->
<dom-module id="px-simple-horizontal-bar-chart">
<template>
<style include="px-simple-horizontal-bar-chart-styles"></style>
<svg class="px-simple-horizontal-bar-chart-svg"></svg>
</template>
</dom-module>
<script>
Polymer({
is: 'px-simple-horizontal-bar-chart',
behaviors: [
PxSimpleChartCommonBehavior.common,
PxSimpleChartCommonBehavior.colors
],
_defaultMeasurements: {
_legendBoxSize: 12,
_legendBoxHeight: 12,
_legendBoxWidth: 3,
_legendMargin: 5,
_legendTextWidth: 115,
_legendPadding: 19,
_legendMarginTop: 8,
_barPadding: 2,
_minimumBarHeight: 10
},
properties: {
/**
* This attribute defines the series data to be charted. It needs to
* be passed in as a 1D array or as a multi-dimensional array containing
* one or more arrays of numeric values.
*/
chartData: {
type: Array,
observer: '_drawChart',
value: function() {
return [29,20,15,18,8,10];
}
},
/**
* This attribute defines the custom text labels for your bar chart
* legend. Pass in the values as an array of strings.
*/
legendLabels: {
type: Array,
observer: '_drawChart',
value: function() {
return ['Bar One','Bar Two','Bar Three','Bar Four','Bar Five','Bar Six','Bar Seven','Bar Eight','Bar Nine','Bar Ten','Bar Eleven','Bar Twelve','Bar Thirteen','Bar Fourteen','Bar Fifteen'];
}
},
/**
* This attribute configures custom bar colors. Pass in the desired
* values as an array of hexadecimal value color strings. Prefer
* settings the colors as CSS style variables to fit in with
* other theming capabilities. Setting the colors attribute directly
* will override all default colors and any CSS style variable themes.
*
*
* Example setting colors as an attribute:
*
* ```
* <px-simple-horizontal-bar-chart
* ...
* colors=['#5da5da', '#faa43a', '#60bd68']>
* </px-simple-horizontal-bar-chart>
* ```
*
* Example setting colors with CSS style variables:
*
* ```
* <style>
* :root {
* --px-vis-series-color-0: #5da5da;
* --px-vis-series-color-1: #faa43a;
* --px-vis-series-color-2: #60bd68;
* }
* </style>
* <px-simple-horizontal-bar-chart ...>
* </px-simple-horizontal-bar-chart>
* ```
*/
colors: {
type: Array,
observer: '_drawChart',
value: function() {
return [];
}
},
/**
* Sets the format to apply to the labels beside each bar. Choose from
* 'percentage' or 'values'.
*/
barLabels: {
type: String,
observer: '_drawChart',
value: 'percentage'
},
/**
* The data's minimum extent on the X-axis. Used to set the D3 domain on the X scale.
* You should only reset if you have a negative value. If you have a
* positive value, leave it at default 0.
*/
domainMin: {
type: Number,
observer: '_drawChart',
value: 0
},
/**
* The data's maximum extent on the X-axis. Used to set the D3 domain on the X scale.
*/
domainMax: {
type: Number,
observer: '_drawChart'
}
},
// Watch changes to dataVisColors or seriesConfig to redraw chart with
// appropriate theme colors.
observers: ['_drawChart(seriesColorList.*,seriesConfig.*)'],
_setDefaultMeasurements: function() {
for (var prop in this._defaultMeasurements) {
this[prop] = this._defaultMeasurements[prop];
};
this._legendColumnWidth = this._legendBoxSize + this._legendMargin + this._legendTextWidth;
this._legendItemHeight = this._legendMargin + this._legendBoxSize;
},
/**
* Retrieves the colors for the chart at index `i`. Handles a few cases
* where colors can be configured for the chart:
*
*
* # Case 1: Developer sets the `colors` attribute
*
* The element could be used with a `colors` attribute:
*
* ```
* <px-simple-horizontal-bar-chart colors=['#aaa','#bbb','#ccc'] ...>
* </px-simple-horizontal-bar-chart>
* ```
*
* If it is used with a `colors` attribute and a theme, the theme is
* overriden and ignored:
*
* ```
* <style>
* :root {
* --px-vis-series-color-0: #aaa;
* --px-vis-series-color-1: #bbb;
* --px-vis-series-color-2: #ccc;
* ...
* };
* </style>
* <px-simple-horizontal-bar-chart ...>
* </px-simple-horizontal-bar-chart>
* ```
*
* In this case, method loops through the `colors` attribute to retrieve
* colors using `_getLocalColor`.
*
*
* # Case 2: Developer does not set `colors` attribute
*
* The element could be used without a `colors` attribute or theme:
*
* ```
* <px-simple-horizontal-bar-chart colors=['#aaa','#bbb','#ccc'] ...>
* </px-simple-horizontal-bar-chart>
* ```
*
* Or it could be used without a `colors` attribute and with a theme:
*
* ```
* <style>
* :root {
* --px-vis-series-color-0: #aaa;
* --px-vis-series-color-1: #bbb;
* --px-vis-series-color-2: #ccc;
* ...
* };
* </style>
* <px-simple-horizontal-bar-chart ...>
* </px-simple-horizontal-bar-chart>
* ```
*
* In this case, method returns the default or theme colors by calling
* `_getDataVisColor` (from `pxSimpleChartCommonBehavior`) to get the
* data vis colors supplied by `PxSimpleChartCommonBehavior.colors`.
*/
_getColor: function(index) {
if (this.colors.length) {
// Get from colors attribute
return this._getLocalColor(index);
} else {
// Get the default or themed data vis color
return this._getDataVisColor(index);
}
},
/**
* Loops through the supplied colors in `colors` attribute and returns
* the color at `index`.
*/
_getLocalColor: function(index) {
if(index >= 0 && index < this.colors.length) {
return this.colors[index];
} else {
// recurse and loop through color list
return this._getColor(Math.abs(this.colors.length - index));
}
},
_drawChartDebounced: function() {
if (this.chartData && this.chartData.length > 0 && this.svg) {
this._setDefaultMeasurements();
// clear the svg element
this._clearSVG(this.svg);
// _setDimensions sets this.widthValue and this.heightValue
this._setDimensions();
var drawLegend = this._isThereEnoughSpaceForLegend();
this._setSizes(drawLegend);
this._drawSVG();
this._setScales();
this._drawBars();
this._drawLeftLine();
if (drawLegend) {
this._drawLegend();
}
// add css class to svg elements using method from pxD3Util
this._addStyleScope(this.svg);
} else {
var that = this;
var timeout = setTimeout(function() {
that._drawChartDebounced();
}, 100);
}
},
_setSizes: function(drawLegend) {
this.chartWidth = this.widthValue - this._getBarLabelWidth();
var availableHeight = drawLegend
? this.heightValue - this._getLegendHeight()
: this.heightValue;
this.barHeight = Math.round(availableHeight / this.chartData.length) - this._barPadding;
if (this.barHeight < this._minimumBarHeight) {
console.error('The bar height is too low. In order to improve rendering of the chart, increase the height of the chart or remove data points being charted.');
} else if (this.barHeight < 1) {
console.error('The height of your chart is too low to render the component.');
};
this.chartHeight = (this.barHeight + this._barPadding) * (this.chartData.length) - this._barPadding;
},
// TODO: write this function to calculate based on label text strings
_getBarLabelWidth: function() {
return 60;
},
_drawSVG: function() {
this.svg.attr('width', this.widthValue).attr('height', this.heightValue);
},
_setScales: function() {
// no yscale necessary
if (this.domainMax) {
if (this.domainMax < d3.max(this.chartData)) {
console.error("domainMax input is less than the Max Chart Data");
this.xScale = d3.scale.linear().domain([
0,
d3.max(this.chartData)
]).range([0, this.chartWidth]);
} else {
this.xScale = d3.scale.linear().domain([this.domainMin, this.domainMax]).range([0, this.chartWidth]);
};
} else {
this.xScale = d3.scale.linear().domain([
0,
d3.max(this.chartData)
]).range([0, this.chartWidth]);
};
},
_getMaxNumberOfColumns: function() {
return Math.floor(this.widthValue / this._legendColumnWidth);
},
/**
* _getMaxLegendColumns() calculates the number of columns necessary
* depends on variables legendPadding, legendColumnWidth,
* this.heightValue, this.widthValue
*
* @return {Number} numColumns
*/
_getMaxLegendColumns: function() {
var maxColumns = this._getMaxNumberOfColumns();
if ((this.chartData.length / maxColumns) >= 1) {
// all columns will be used
return Math.floor(maxColumns);
} else {
// only some of the columns will be used
var columnsUsed = Math.floor(this.chartData.length % maxColumns);
if (columnsUsed === 0) {
return maxColumns;
} else {
return columnsUsed;
}
};
},
_getMaxItemsInColumn: function() {
return Math.ceil(this.chartData.length / this._getMaxLegendColumns());
},
/**
* _getLegendHeight() calculates the necessary height of legend
*
* @param {Object} chartData
* @return {Number} numColumns
*/
_getLegendHeight: function() {
return (this._getMaxItemsInColumn() * this._legendItemHeight) + this._legendMarginTop;
},
_drawLegendBox: function(x, y, color) {
var boxNode = this.svg.append("rect").attr("class", "legend-box").attr("x", x).attr("y", y).attr("width", this._legendBoxWidth).attr("height", this._legendBoxSize).attr("fill", color);
this._addStyleScopeToElement(boxNode);
return boxNode;
},
_drawLegendLabel: function(x, y, labelText) {
var textNode = this.svg.append("text").attr("class", "legend-text").attr("x", x + 3).attr("y", y + 10).text(labelText);
this._addStyleScopeToElement(textNode);
return textNode;
},
_drawLegendItem: function(i) {
var labelText = this.legendLabels[i];
var color = this._getColor(i);
var maxItemsInColumn = this._getMaxItemsInColumn();
var targetWidth = this._legendTextWidth;
var columnNumber = Math.floor(i / maxItemsInColumn);
var x = columnNumber * this._legendColumnWidth;
var columnTop = this._legendItemHeight * maxItemsInColumn * columnNumber;
var y = (i * this._legendItemHeight) + this.chartHeight - columnTop + this._legendMarginTop;
if (typeof y !== Number) {
// console.log(y, targetWidth, columnNumber, columnTop, maxItemsInColumn, this._legendItemHeight, this.chartHeight, this._legendMarginTop);
}
var that = this;
var labelTextPromise = this._shortenText(labelText, targetWidth);
labelTextPromise.then(function(labelText) {
that._drawLegendBox(x, y, color);
that._drawLegendLabel(x + that._legendMargin, y, labelText);
}).catch(function(reason) {
console.log('labelTextPromise rejected:', reason)
});
},
_shortenText: function(text, targetWidth) {
var that = this;
return new Promise(function(resolve, reject) {
var widthPromise = that._calculateTextWidth(text, "legend-text");
widthPromise.then(function(width) {
if (width <= targetWidth) {
resolve(text);
} else {
var newText = text.substring(0, text.length - 4) + '...';
var shortenPromise = that._shortenText(newText, targetWidth);
shortenPromise.then(function(promiseText) {
resolve(promiseText);
}).catch(function(reason) {
console.log('shortenPromise failed. Reason: ', reason);
});
}
}).catch(function(reason) {
console.log('widthPromise failed. Reason: ', reason)
});
});
},
_getNumberOfColumnsUsed: function() {
return Math.ceil(this.chartData.length / this._getMaxItemsInColumn());
},
_getWidthUsedByLegend: function() {
return this._legendColumnWidth * this._getNumberOfColumnsUsed();
},
_drawLegend: function() {
var dataLength = this.chartData.length;
var i;
if (this.legendLabels.length < this.chartData.length) {
console.error('There are not enough legend-labels defined for the chart data.')
};
var diff = this.widthValue - this._getWidthUsedByLegend();
this._legendTextWidth += Math.floor(diff / this._getNumberOfColumnsUsed()) - this._legendMargin;
this._legendColumnWidth = this._legendBoxSize + this._legendMargin + this._legendTextWidth;
for (i = 0; i < dataLength; i++) {
this._drawLegendItem(i);
};
},
_drawBar: function(x, y, width, height, i, color) {
this.svg.append("rect").attr("class", "bar").attr("x", x).attr("y", y).attr("width", width).attr("height", height).attr("fill", i);
},
_calculateLabelCenterOffset: function(rectObject) {
var height = rectObject.height;
var diff = Math.abs(this.barHeight - height);
var offset = (diff / 2) - this._barPadding + height;
return Math.round(offset - offset * 0.10);
},
_drawBarLabel: function(x, y, labelText) {
// use common function _calculateTextWidth to calc label width
var textSizePromise = this._calculateTextSize(labelText);
var widthValue = this.widthValue;
var that = this;
textSizePromise.then(function(rectObject) {
var textWidth = rectObject.width;
var labelOffset = that._calculateLabelCenterOffset(rectObject);
var textNode = that.svg.append("text").attr("class", "bar-label").attr("x", widthValue - textWidth - 10).attr("y", y + labelOffset).attr("width", textWidth).text(labelText);
that._addStyleScopeToElement(textNode);
}).catch(function(reason) {
console.log('textSizePromise rejected: ', reason);
});
},
_sum: function(arr) {
return arr.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
},
_getPercent: function(value, sum) {
return Math.round(value / sum * 100);
},
_getPercentAccurate: function(value, sum) {
return Math.round((value / sum * 100) * 10) / 10;
},
// returns boolean defining need for floating point in percentage label
_percentagesNeedFloatingPoint: function(arr) {
var sum = this._sum(arr);
var i = 0,
len = arr.length,
percentageSum = 0;
for (i = 0; i < len; i++) {
percentageSum += this._getPercent(arr[i], sum);
};
return (percentageSum !== 100);
},
_drawBars: function() {
// loop through the chartData and draw a bar for each value
var length = this.chartData.length,
i = 0,
value,
labelText,
barWidth,
y,
x,
color;
var sum = this._sum(this.chartData);
var drawBars = this._isThereEnoughSpaceForBarLabels();
// choose the correct percentage calculation function to be used on each label
var percentFunction = this._percentagesNeedFloatingPoint(this.chartData)
? this._getPercentAccurate
: this._getPercent;
for (i; i < length; i++) {
value = this.chartData[i];
if (this.barLabels == 'values') {
textLabel = value;
} else if (value == 0) {
textLabel = value + "%";
} else {
textLabel = percentFunction(value, sum) + "%";
};
barWidth = Math.floor(this.xScale(value));
x = 0;
y = i * (this.barHeight + this._barPadding);
color = this._getColor(i);
this._drawBar(x, y, barWidth, this.barHeight, color);
if (drawBars) {
this._drawBarLabel(x, y, textLabel);
}
};
},
_drawLeftLine: function() {
this.svg.append("line").attr("class", "bar-chart-left-line").attr("x1", 0).attr("y1", 0).attr("x2", 0).attr("y2", this.chartHeight);
},
_minChartHeight: function(minBarHeight) {
return (minBarHeight * this.chartData.length) + this._legendMarginTop + (this._legendItemHeight * this._getMaxItemsInColumn());
},
_isThereEnoughSpaceForBarLabels: function() {
return this._minChartHeight(14) <= this.heightValue;
},
_isThereEnoughSpaceForLegend: function() {
return this._minChartHeight(3) <= this.heightValue;
}
});
</script>