Debian Codegraph @

js/src/ColorUtils.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 // var d3 =Object.assign({}, require("d3-array"), require("d3-scale"));
18 import colorbrewer from './colorbrewer';
19
20 const default_scheme = 'RdYlGn';
21 //
22 // Returns the maximum number of colors available in the colorbrewer object
23 function get_max_index(color_object) {
24 return d3.max(Object.keys(color_object).map(Number));
25 }
26
27 export function cycle_colors(colors, count) {
28 const colors_len = colors.length;
29 if (colors_len > count) {
30 return colors.slice(0, count);
31 } else {
32 let return_array = [];
33 let iters = Math.floor(count / colors_len);
34 for (; iters > 0; iters--) {
35 return_array = return_array.concat(colors);
36 }
37 return return_array.concat(colors.slice(0, count % colors_len));
38 }
39 }
40
41 export function cycle_colors_from_scheme(scheme, num_steps) {
42 scheme = scheme in colorbrewer ? scheme : default_scheme;
43 const color_set = colorbrewer[scheme];
44
45 // Indices of colorbrewer objects are strings
46 let color_index = num_steps.toString();
47
48 if (num_steps === 2) {
49 return [color_set[3]['0'], color_set[3]['2']];
50 } else if (color_index in color_set) {
51 return color_set[color_index];
52 } else {
53 color_index = get_max_index(color_set).toString();
54 return this.cycle_colors(color_set[color_index], num_steps);
55 }
56 }
57
58 export function get_linear_scale(scheme) {
59 scheme =
60 scheme in colorbrewer && !(colorbrewer[scheme]['type'] === 'qual')
61 ? scheme
62 : default_scheme;
63 const color_set = colorbrewer[scheme];
64 const color_index = get_max_index(color_set).toString();
65
66 const colors = color_set[color_index];
67 const scale = d3.scaleLinear().range(colors);
68 return scale;
69 }
70
71 export function get_ordinal_scale(scheme, num_steps) {
72 const scale = d3.scaleOrdinal();
73 scale.range(this.cycle_colors_from_scheme(scheme, num_steps));
74 return scale;
75 }
76
77 export function get_linear_scale_range(scheme) {
78 return this.get_linear_scale(scheme).range();
79 }
80
81 export function get_ordinal_scale_range(scheme, num_steps) {
82 return this.get_ordinal_scale(scheme, num_steps).range();
83 }