-
Notifications
You must be signed in to change notification settings - Fork 0
/
d3.util.js
349 lines (320 loc) · 11.6 KB
/
d3.util.js
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
/*!
* Miscellaneous personal utilities for d3.
* Copyright (c) 2011, Nick Rabinowitz / Google Ancient Places Project
* Licensed under the BSD License.
*/
/**
* @namespace Utility namespace
*/
d3.util = d3.util || {};
/**
* Determine whether to use black or white text over a given color.
* @param {String|Color} fill Color under the text
* @return {String} Black or white, in hex
*/
d3.util.textOnFill = function(fill) {
fill = d3.rgb(fill);
var sum = fill.r + fill.g + fill.b;
return sum/3 < 152 ? '#fff' : '#000';
};
/**
* Decorator: Takes a function and adds the ability to add chainable getter/setters.
* @param {Function(selection)} func Function to decorate
* @return {Function(selection, options)} Decorated function
*/
d3.util.component = function(func) {
var options = {},
f = function(selection) {
func(selection, options);
};
f.option = function(name, defaultValue) {
if (name == 'option' || name == 'options') return;
options[name] = defaultValue;
f[name] = function(value) {
if (!arguments.length) return options[name];
options[name] = value;
return f;
}
return f;
}
return f;
};
/**
* Color legend. Makes a configurable bar with blocks of color and
* optional numbers at both ends and in the middle.
*/
d3.util.colorLegend = function() {
return d3.util.component(function(container, opts) {
if (!opts.scale || !opts.scale.ticks) return;
var vertical = opts.height > opts.width,
ticks = opts.scale.ticks(opts.ticks),
length = ticks.length,
labelStyler = opts.labelStyler || function() {};
// legend colors
container.selectAll('rect.' + opts.cssClass)
.data(ticks)
.enter().append('svg:rect')
.attr('class', opts.cssClass)
.attr('x', vertical ? 0 : function(d,i) { return i * (opts.width / length) })
.attr('y', !vertical ? 0 : function(d,i) { return i * (opts.height / length) })
.attr('width', vertical ? opts.width : opts.width / length)
.attr('height', !vertical ? opts.height : opts.height / length)
.style('fill', opts.scale);
// legend label setup
var domain = opts.scale.domain(),
min = domain[0],
max = domain[domain.length - 1],
labelPos = d3.scale.linear()
.domain([min, max])
.range([0, vertical ? opts.height : opts.width]),
labels = [];
if (opts.startLabel) labels.push(min);
if (opts.middleLabel) labels.push(max/2);
if (opts.endLabel) labels.push(max);
// add legend labels
container.selectAll('text.' + opts.cssClass)
.data(labels)
.enter().append('svg:text')
.attr('class', opts.cssClass)
.attr('x', vertical ? opts.width : labelPos)
.attr('y', vertical ? labelPos : opts.height)
.attr("dx", vertical ? 5 : 0)
.attr("dy", !vertical ? '1em' : function(d) {
return !opts.alignLabels ? '.35em' :
d == min ? '.8em' :
d == max ? 0 :
'.35em';
})
.attr('text-anchor', vertical ? 'start' : function(d) {
return !opts.alignLabels ? 'middle' :
d == min ? 'start' :
d == max ? 'end' :
'middle';
})
.text(opts.format)
.call(labelStyler);
})
// add options with defaults
.option('width', 200)
.option('height', 20)
.option('scale')
.option('format', d3.format(','))
.option('ticks', 10)
.option('startLabel', true)
.option('endLabel', true)
.option('middleLabel')
.option('cssClass', 'legend')
.option('labelStyler')
.option('alignLabels', false);
};
/**
* Size legend. Makes a configurable set of circles with size labels.
*/
d3.util.sizeLegend = function() {
return d3.util.component(function(container, opts) {
if (!opts.scale || !opts.scale.ticks) return;
var vertical = opts.vertical && !opts.horizontal,
padding = opts.padding || vertical ? 3 : 20,
scale = opts.scale,
ticks = scale.ticks(opts.ticks);
if (!ticks[0]) {
ticks = scale.ticks(opts.ticks + 1).slice(1);
}
var length = ticks.length,
maxRadius = scale(ticks[length-1]),
offset = Math.max(maxRadius, 15) + padding,
circleStyler = opts.circleStyler || function() {},
labelStyler = opts.labelStyler || function() {};
var legend = container.selectAll('g')
.data(ticks)
.enter().append("svg:g")
.attr('transform', function(d,i) {
var xoff = vertical ? maxRadius : i*offset,
yoff = !vertical ? maxRadius : i*offset;
return 'translate(' + xoff + ',' + yoff +')';
});
legend.append('svg:circle')
.attr('cx', maxRadius)
.attr('cy', maxRadius/2)
.attr('r', scale)
.attr('fill', '#ccc')
.call(circleStyler);
legend.append('svg:text')
.attr('x', vertical ? maxRadius * 2 + 5 : maxRadius)
.attr('y', !vertical ? maxRadius * 2 : offset/2)
.attr('dy', vertical ? 0 : '.8em')
.attr('text-anchor', vertical ? 'start' : 'middle')
.text(opts.format)
.call(labelStyler);
})
// add options with defaults
.option('scale')
.option('vertical', true)
.option('horizontal')
.option('format', d3.format(','))
.option('ticks', 3)
.option('padding')
.option('cssClass', 'legend')
.option('circleStyler')
.option('labelStyler');
};
/**
* Get a color scale from min/max and an arbitrary number of colors
* @param {Number} min Minimum value
* @param {Number} max Maximum value
* @param {Color[]} colors Range of colors
*/
d3.scale.color = function(min, max, colors) {
var interval = (max - min) / (colors.length-1),
scale = d3.scale.linear()
.domain(colors.map(function(c,i) { return min + i * interval }))
.range(colors);
return scale;
};
// Misc common formats, added to d3.format as a convenience
d3.format.percentage = d3.format('%');
d3.format.comma = d3.format(',');
/**
* Format large numbers in a concise 1- to 3-digit style, with
* a magnitude suffix if necessary
* @param {Number} d Number to format
*/
d3.format.big = function(d) {
// determine order of magnitude
var orders = [
['', 1],
['K', 1000],
['M', 1000000],
['Bn', 1000000000]
],
order = 0,
format;
while (order < orders.length-1 && d > orders[order+1][1]) order++;
order = orders[order];
d = d / order[1];
format = d3.format(d >= 100 || d - ~~d < .059 ? '.0f' : '.1f');
return format(d) + order[0];
};
d3.format.amount = function(d) { return '$' + d3.format.big(d) };
// geo utilities
if (d3.geo) {
/**
* Fit projection to a given bounding box, based on geodata
* @param {d3.projection} projection projection to fit
* @param {geojson} data geojson
* @param {Array} box x,y bounding box, as [[x1,y1],[x2,y2]]
* @param {Object} [options] Container for optional params
* @param {Number} [options.padding] padding on bounding box
* @param {Boolean} [options.center] whether to center the points or align to top left
* @return {d3.projection} projection, with scale and translate set appropriately
*/
d3.geo.fitProjection = function(projection, data, box, options) {
var opts = options || {},
padding = opts.padding || 0,
center = opts.center,
// get the bounding box for the data - might be more efficient approaches
left = Infinity,
bottom = -Infinity,
right = -Infinity,
top = Infinity;
// set up bounding box
if (padding) {
box[0][0] += padding;
box[0][1] += padding;
box[1][0] -= padding;
box[1][1] -= padding;
}
// reset projection
projection
.scale(1)
.translate([0, 0]);
// find bounding box (almost)
data.features.forEach(function(feature) {
d3.geo.bounds(feature).forEach(function(coords) {
coords = projection(coords);
var x = coords[0],
y = coords[1];
if (x < left) left = x;
if (x > right) right = x;
if (y > bottom) bottom = y;
if (y < top) top = y;
});
});
// project the bounding box, find aspect ratio
function width(bb) {
return (bb[1][0] - bb[0][0])
}
function height(bb) {
return (bb[1][1] - bb[0][1]);
}
function aspect(bb) {
return width(bb) / height(bb);
}
var startbox = [[left, top], [right, bottom]],
a1 = aspect(startbox),
a2 = aspect(box),
widthDetermined = a1 > a2,
scale = widthDetermined ?
// scale determined by width
width(box) / width(startbox) :
// scale determined by height
height(box) / height(startbox),
// set x translation
transX = box[0][0] - startbox[0][0] * scale,
// set y translation
transY = box[0][1] - startbox[0][1] * scale;
// center if requested
if (center) {
if (widthDetermined) {
transY = transY - (transY + startbox[1][1] * scale - box[1][1])/2;
} else {
transX = transX - (transX + startbox[1][0] * scale - box[1][0])/2;
}
}
return projection.scale(scale).translate([transX, transY])
};
/**
* Version of the mercator projection that allows setting the origin.
* Works with point data, mixed results with path data.
*/
d3.geo.mercator_origin = function() {
var d3_geo_radians = Math.PI / 180,
scale = 500,
translate = [480, 250],
origin = [0,0];
function mercator(coordinates) {
var x = (coordinates[0] + origin[0]) / 360,
y = -(Math.log(Math.tan(Math.PI / 4 + coordinates[1] * d3_geo_radians / 2)) / d3_geo_radians) / 360;
// fix x
x += (x < -.5) ? 1 : (x > .5) ? -1 : 0;
return [
scale * x + translate[0],
scale * Math.max(-.5, Math.min(.5, y)) + translate[1]
];
}
mercator.invert = function(coordinates) {
var x = (coordinates[0] - translate[0]) / scale,
y = (coordinates[1] - translate[1]) / scale;
return [
360 * x,
2 * Math.atan(Math.exp(-360 * y * d3_geo_radians)) / d3_geo_radians - 90
];
};
mercator.scale = function(x) {
if (!arguments.length) return scale;
scale = +x;
return mercator;
};
mercator.translate = function(x) {
if (!arguments.length) return translate;
translate = [+x[0], +x[1]];
return mercator;
};
mercator.origin = function(x) {
if (!arguments.length) return origin;
origin = x;
return mercator;
};
return mercator;
};
}