forked from mode/alamode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alamode.js
3251 lines (2628 loc) · 100 KB
/
alamode.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
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// alamode.js
//
// Visualizations for Mode reports
var version = "0.23";
var alamode = {
reportError: function(msg) {
$("<h1 class='mode-error'>").text(msg).prependTo(document.body);
},
getColumnsFromQuery: function(queryName) {
var columns = datasets.filter(function(d) { if (d) { return d.queryName == queryName;}; })[0];
if (!columns) {
alamode.reportError("No such query: '" + queryName + "'");
return [];
}
return columns.columns
},
getDataFromQuery: function(queryName) {
var data = datasets.filter(function(d) { if (d) { return d.queryName == queryName;}; })[0];
if (!data) {
alamode.reportError("No such query: '" + queryName + "'");
return [];
}
return data.content;
},
makeId: function(chars) {
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
text = "";
for (var i=0; i < chars; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
},
addContainerElement: function(el, clear) {
clear = clear || false;
id = alamode.makeId(10);
if (el == "body") {
$("<div id='" + id + "'></div>").addClass(id).addClass("mode-graphic-container").appendTo(".mode-content");
} else if ($(el).length === 0) {
alamode.reportError("No such element: '" + el + "'");
} else {
if (clear) {
$(el).empty();
}
$(el).addClass("mode-graphic-container");
$(el).addClass(id);
}
return "." + id;
},
addLinksToTables: function(o) {
var tableId = "#" + o["table_id"],
linkColumns = o["link_columns"],
linkURLs = o["link_urls"],
queryName = o["query_name"],
openInNewTab = o["open_in_new_tab"] || false;
var linkFormat = [];
var colIndex = {};
linkColumns.forEach(function(l,i) {
linkFormat.push( { column: l, link_string: linkURLs[i] });
})
var data = alamode.getDataFromQuery(queryName),
columns = alamode.getColumnsFromQuery(queryName);
setTimeout(function(){
drawLinks(linkFormat)
},1000)
$(tableId).mousemove(function() {
drawLinks(linkFormat)
})
function drawLinks(linkFormat) {
var tableDiv = $(tableId + " table"),
tableHeader = $(tableId + " .js-header-table"),
headers = !tableHeader ? $(tableHeader).find("th") : $(tableId + " .js-col-header"),
rows = tableDiv.find("tr"),
columnIndex = 0;
headers.each(function() {
text = $(this).find(".axel-table-header-label").text()
columnIndex = $(this).attr("data-axel-column")
colIndex[text] = columnIndex - 1
})
rows.each(function(i) {
if (i > 0 && i <= data.length) {
var cells = $(this).find("td"),
rowKey = cells.first().attr("data-axel-rowkey");
linkFormat.forEach(function(l) {
var columnToShow = colIndex[l.column],
cellContent = cells.eq(columnToShow).text();
url = l.link_string;
while (url.indexOf("{{") != - 1) {
var chars = url.length,
start = url.indexOf("{{"),
end = url.substring(start+2,chars).indexOf("}}"),
cName = url.substring(start+2,start+end+2),
full = url.substring(start,start+end+4),
col = colIndex[cName],
content = data[rowKey][cName];
url = url.replace(full,content);
}
var target = (openInNewTab) ? "_blank" : "_top";
var link_html = "<a target='" + target + "' href='" + encodeURI(url) + "'>" + cellContent + "</a>";
cells.eq(columnToShow).html(link_html);
})
}
})
}
},
customChartColors: function(o) {
var charts = o["charts"],
colors = o["colors"],
opacities = o["opacity"],
lineDashes = o["line_dashes"];
if (charts == "all") {
charts = [];
$("mode-chart").each(function(){ charts.push(this.id); });
}
function prepColors(id, colorList) {
var chart = $("#" + id),
series = chart.find('.nv-bar').length > 0 ? chart.find('.nv-group') : chart.find('.nv-line').length > 0 || chart.find('.nv-areaWrap').length > 0 ? chart.find('.nv-noninteractive') : chart.find('.nv-pie .nv-slice'),
seriesCount = series.length,
legend = chart.find(".nv-series .nv-legend-symbol");
var colors = {};
var m = {};
var r = {};
var counter = 0;
if (legend.length == 0 && seriesCount <= 1) {
m[0] = counter;
r[counter] = 0;
colors[0] = colorList[0];
} else if (legend.length == 0 && seriesCount > 1) {
for (i = 0; i < seriesCount; i++) {
m[i] = i;
colors = colorList;
}
} else {
for (i = 0; i < legend.length; i++) {
colors[i] = colorList[i % Object.keys(colorList).length];
}
}
legend.each(function(i) {
if ($(this).css("fill-opacity") == 1) {
m[i] = counter;
r[counter] = i;
counter += 1;
} else {
m[i] = -1;
}
})
return {chart: chart, legend: legend, colors: colors, m: m, r: r, seriesCount: seriesCount};
}
function drawColors(id, colorList) {
var data = prepColors(id, colorList),
chart = data.chart,
colors = data.colors,
m = data.m;
for (var i in colors) {
chart.find(".nv-linesWrap .nv-groups .nv-series-" + m[i]).css( {"fill":colors[i],"stroke":colors[i] });
chart.find(".nv-barsWrap .nv-groups .nv-series-" + m[i] + " rect").css( {"fill":colors[i],"stroke":colors[i] });
chart.find(".nv-linePlusBar .nv-barsWrap .nv-bars rect").each(function(index){
$(this).css({"fill": colors[0],"stroke": colors[0]});
});
chart.find(".nv-linePlusBar .nv-linesWrap .nv-groups .nv-series-0").css({"fill": colors[1],"stroke": colors[1]});
chart.find(".nv-scatterWrap .nv-groups .nv-series-" + m[i]).css( {"fill":colors[i],"stroke":colors[i] });
chart.find(".nv-areaWrap .nv-area-" + m[i]).css( {"fill":colors[i],"stroke":colors[i] });
chart.find(".nv-pie .nv-slice").each(function(i) { $(this).css( {"fill":colors[i],"stroke":colors[i]}); });
}
for (var i in opacities) {
chart.find(".nv-linesWrap .nv-groups .nv-series-" + m[i]).css( {"opacity":opacities[i]} );
chart.find(".nv-barsWrap .nv-groups .nv-series-" + m[i] + " rect").css( {"opacity":opacities[i]} );
if (i == 0){
chart.find(".nv-linePlusBar .nv-barsWrap .nv-bars rect").each(function(index){
$(this).css({
"opacity": opacities[i]
});
});
chart.find(".nv-linePlusBar .nv-linesWrap .nv-groups .nv-series-0").css({"opacity": opacities[1]});
}
chart.find(".nv-scatterWrap .nv-groups .nv-series-" + m[i]).css( {"opacity":opacities[i]} );
chart.find(".nv-areaWrap .nv-area-" + m[i]).css( {"opacity":opacities[i]} );
chart.find(".nv-pie .nv-slice").each(function(i) { $(this).css( {"opacity":opacities[i]} ); });
}
for (var i in lineDashes) {
chart.find(".nv-linesWrap .nv-groups .nv-series-" + m[i]).css( {"stroke-dasharray":lineDashes[i]} );
}
chart.find(".nv-legendWrap .nv-series .nv-legend-symbol").each(function(i) {
$(this).css({"fill":colors[i],"stroke":colors[i]});
})
}
function onMouseMove(id, colorList) {
var chart = $("#" + id);
$(chart).mousemove(function() {
var data = prepColors(id, colorList),
legend = data.legend,
colors = data.colors,
r = data.r,
m = data.m,
seriesCount = data.seriesCount,
isAreaLength = isArea = chart.find(".nv-area").length,
isBarLength = chart.find(".nv-bar").length,
isLineLength = chart.find(".nv-line").length;
$("html").find(".nvtooltip table .legend-color-guide").each(function(i) {
if (legend.length == 0 && isBarLength == 0) {
$(this).find("div").css({"background-color":colors[m[i]]});
} else if (isLineLength > 0 && isBarLength > 0) {
var lineColor = chart.find(".nv-linePlusBar .nv-linesWrap .nv-groups .nv-series-0").css("fill"),
barColor = chart.find(".nv-linePlusBar .nv-barsWrap .nv-bars rect").css("fill");
if ($(this).closest(".nvtooltip").find(".key")[0].innerText == "") {
$(this).find("div").css("background-color", barColor)
} else {
$(this).find("div").css("background-color", lineColor);
}
} else if (isBarLength > 0) {
if (seriesCount == 1) {
$(this).find("div").css({"background-color": colors[r[seriesCount - i - 1]]});
}
} else if (isAreaLength > 0) {
$(this).find("div").css({"background-color": colors[isAreaLength - i - 1]});
} else {
$(this).find("div").css({"background-color":colors[i]});
}
})
var sliceColor = chart.find(".nv-pie .nv-slice.hover").css("fill");
$("html").find(".nvtooltip table .legend-color-guide div").css("background-color",sliceColor)
})
$(chart).mouseleave(function() {
$("html").find(".nvtooltip table .legend-color-guide").remove();
})
}
setInterval(function () {
charts.forEach(function(c) {
drawColors(c,colors)
})
}, 500)
charts.forEach(function(c) {
onMouseMove(c, colors);
})
},
addTotalsRow: function(o) {
var queryName = o["query_name"],
selectedTable = o["table_id"] || "",
tableId = "#" + selectedTable,
resultColumns = alamode.getColumnsFromQuery(queryName),
data = alamode.getDataFromQuery(queryName),
selectedColumns = o["columns_with_totals"],
userProvidedFmt = o["fmt"];
var fmt = userProvidedFmt || d3.format(",");
var columnsWithSums = getColumns(selectedColumns),
totals = makeSums(columnsWithSums);
function getColumns(selectedColumns) {
numberColumns = _.map(_.filter(resultColumns,function(c) {
return ["number","integer","float"].indexOf(c.type) != -1;
}),"name")
if (selectedColumns == "all") {
return numberColumns;
} else {
return _.intersection(selectedColumns, numberColumns);
}
}
function makeSums(columnsWithSums) {
var sumObject = [];
resultColumns.forEach(function(c,i) {
if (columnsWithSums.indexOf(c.name) == -1) {
var obj = {idx: i, name: "", total: ""};
} else {
var values = _.map(data, c.name),
total = d3.sum(values);
var obj = {idx: i, name: c.name, total: total}
}
sumObject.push(obj)
})
return sumObject;
}
function makeRow(totals) {
var rowString = "<tr><td>TTL</td>";
totals.forEach(function(t) {
if (t.total != "") {
rowString = rowString + "<td class='cell-type-number'>" + fmt(t.total) + "</td>"
} else {
rowString = rowString + "<td></td>"
}
})
return rowString + "</tr>"
}
setTimeout(function(){
if (tableId == "#") {
table = $(".main-table")
container = $(".js-table-content-container")
} else {
table = $(tableId + " .main-table")
container = $(tableId + " .js-table-content-container")
}
var lastRow = table.find("tr:last")
var totalRow = makeRow(totals)
var tableHeight = container.css("height")
var tableHeightInt = +tableHeight.match(/\d+/)[0]
lastRow.after(totalRow)
container.css("height",tableHeightInt + 26)
},1000);
},
addImagesToTables: function(o) {
var tableId = "#" + o["table"],
imageColumn = o["column"],
imgHeight = o["image_height"] || 100;
setTimeout(function() {
drawImages();
},1000)
$(tableId).keyup(function() {
setTimeout(function() {
drawImages();
},500)
});
$(tableId).mousemove(function() {
drawImages();
})
function drawImages() {
var tableDiv = $(tableId + " table"),
tableHeader = $(tableId + " .js-header-table"),
headers = !tableHeader ? $(tableHeader).find("th") : $(tableId + " .js-col-header"),
rows = tableDiv.find("tr"),
columnIndex = 0;
headers.each(function() {
text = $(this).find(".axel-table-header-label").text()
if (text == imageColumn) {
columnIndex = +$(this).attr("data-axel-column")
}
})
rows.each(function() {
var cells = $(this).find("td");
cells.each(function(i) {
if (i == (columnIndex - 1)) {
var content = $(this).text();
if ($(this).find("img").length == 0) {
$(this).css("text-align","center")
$(this).html("<img style='height: " + imgHeight + "px;' src='" + content + "'>")
}
}
})
})
}
},
resizeChartHeight: function(o) {
var chart = o["chart"],
height = o["height"];
if (chart.slice(0,6) == "python") {
$("#" + chart + " .mode-python").css("height",height)
$("#" + chart + " .mode-python").css("max-height",height)
$("#" + chart + " img").css("max-height",height)
} else {
$("#" + chart + " .chart").css("height",height)
$("#" + chart + " .chart-svg").css("height",height)
}
window.dispatchEvent(new Event('resize'));
},
retentionHeatmap: function(o) {
var queryName = o["query_name"],
cohortColumn = o["cohort_column"],
pivotColumn = o["pivot_column"],
valueColumn = o["value_column"],
// Optional
colors = o["color_gradient"] || ["#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850"],
gradientBy = o["gradient_by"] || "all", // "all" | "cohort_column" | "pivot_column"
gradientColumn = o["gradient_column"] || valueColumn,
totalColumn = o["total_column"],
htmlElement = o["html_element"] || "body",
title = o["title"] || queryName,
pivotLabel = o["pivot_label"] || "",
isPercent = o["value_is_percent"],
precision = o["precision"] || 0;
var data = alamode.getDataFromQuery(queryName),
columns = alamode.getColumnsFromQuery(queryName),
cohorts = _.uniq( _.map(data, cohortColumn) ),
pivots = _.sortBy(_.uniq( _.map(data, pivotColumn) ) );
var uniqContainerClass = alamode.addContainerElement(htmlElement);
if (gradientBy === "cohort_column") {
var colorsByCohort = {};
cohorts.forEach(function (cohort) {
var dataByCohort = data.filter(function (row) {
return row[cohortColumn] === cohort;
});
colorsByCohort[cohort] = d3.scale.quantize()
.domain(d3.extent(dataByCohort, function(d) { return d[gradientColumn]; }))
.range(colors)
})
} else if (gradientBy === "pivot_column") {
var colorsByPivot = {};
pivots.forEach(function (pivot) {
var dataByPivot = data.filter(function (row) {
return row[pivotColumn] === pivot;
});
colorsByPivot[pivot] = d3.scale.quantize()
.domain(d3.extent(dataByPivot, function(d) { return d[gradientColumn]; }))
.range(colors)
})
} else { // table or as a default fallback
var color = d3.scale.quantize()
.domain(d3.extent(data, function(d) { return d[gradientColumn]; }))
.range(colors)
}
d3.select(uniqContainerClass)
.append("div")
.attr("class","mode-graphic-title")
.text(title)
d3.select(uniqContainerClass)
.append("div")
.attr("class","mode-retention-heatmap-label")
.text(pivotLabel)
if (totalColumn) {
headers = [cohortColumn, totalColumn].concat(pivots)
} else {
headers = [cohortColumn].concat(pivots)
}
var table = d3.select(uniqContainerClass).append("table")
.attr("class","mode-retention-heatmap-table");
table.selectAll(".mode-retention-heatmap-table-header")
.data([0])
.enter().append("tr")
.attr("class","mode-retention-heatmap-table-header")
.selectAll("mode-retention-heatmap-table-header-cell")
.data(headers)
.enter().append("td")
.attr("class",function(d) {
if (isNaN(d)) { return "mode-retention-heatmap-table-header-cell heatmap-string"; }
else { return "mode-retention-heatmap-table-header-cell heatmap-number"; }
})
.text(function(d) { return d; })
table.selectAll(".mode-retention-heatmap-table-row")
.data(cohorts)
.enter().append("tr")
.attr("class","mode-retention-heatmap-table-row")
.selectAll(".mode-retention-heatmap-table-cell")
.data(function(d) { return makeRow(data,d); })
.enter().append("td")
.style("background",function(d) { if (checkShade(d)) { return pickColor(d); } })
.attr("class",function(d) { return cellClass(d); })
.text(function(d) { return fmt(d,o); })
function pickColor (entry) {
if (gradientBy === "cohort_column") {
return colorsByCohort[entry.cohort](entry.gradientValue);
} else if (gradientBy === "pivot_column") {
return colorsByPivot[entry.pivot](entry.gradientValue);
}
return color(entry.gradientValue)
}
function checkShade(entry) {
return entry.column == valueColumn && entry.value !== "";
}
function cellClass(entry) {
var type = getDataType(entry.column);
if (type == "float" || type == "integer" || type == "number") {
return "heatmap-number";
} else {
return "heatmap-string";
}
}
function getDataType(column) {
return columns.filter(function(d) { return d.name == column })[0].type;
}
function makeRow(data,cohort) {
var row = [ {column: cohortColumn, value: cohort } ];
if (totalColumn) {
var total = _.filter(data, function(d) { return d[cohortColumn] == cohort; })[0],
totalObject = { column: totalColumn, value: total[totalColumn] };
row = row.concat(totalObject);
}
pivots.forEach(function(p) {
var entryValue = '';
var gradientValue = '';
var matches = _.filter(data, function(d) {
return d[cohortColumn] == cohort && d[pivotColumn] == p
});
if (matches.length > 0) {
entryValue = d3.mean( _.map(matches,valueColumn) );
gradientValue = d3.mean( _.map(matches,gradientColumn) );
}
row = row.concat( {column: valueColumn, value: entryValue, cohort: cohort, pivot: p, gradientValue: gradientValue } )
})
return row;
}
function fmt(entry) {
var type = getDataType(entry.column);
var c = d3.format(","),
p = d3.format("." + precision + "%"),
t = d3.time.format("%b %d, %Y");
if (entry.value == "") {
return entry.value;
} else if (type == "datetime" || type == "timestamp" || type == "date") {
if (typeof moment == "function") {
return moment(entry.value).utc().format("ll")
} else {
return t(new Date(entry.value));
}
} else if (entry.column == totalColumn) {
return c(entry.value);
} else if (entry.column == valueColumn && isPercent) {
return p(entry.value);
} else if (entry.column == valueColumn) {
return c(entry.value);
} else {
return entry.value;
}
}
},
// A simple heatmap to use for any 2-labeled data
// Parameters:
// - query_name: the name of the query that has the source data
// - x_column: the column to show across the top
// - y_column: the column to show down the left side
// - value_column: the column to show in the heatmap boxes
// - max_value: if present, all values greater than this value will be set to the maximum color
// - min_value: if present, all values less than this value will be set to the minimum color
// - color_gradient: if present, overrides the green/red gradient. Should be an array of strings, where each value is a hex color string
// - html_element: The element to add the heatmap to
// - title: The title of the heatmap
// - x_label: The title to show above the x_column values
// - y_label: The title to show above the left column of the heatmap with y_column values
// - value_is_percent: a bool (default false). If it's true, the values will be formatted using d3.format as a percent
// - precision: if value_is_percent is true, this is used as the precision in the d3.format call
simpleHeatmap: function(o) {
var queryName = o["query_name"],
xColumn = o["x_column"],
yColumn = o["y_column"],
valueColumn = o["value_column"],
maxValue = o["max_value"] || Number.MAX_VALUE,
minValue = (o["min_value"]===0) ? 0 : (o["min_value"] || Number.MIN_VALUE ),
// Optional
colors = o["color_gradient"] || ["#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850"],
htmlElement = o["html_element"] || "body",
title = o["title"] || queryName,
xLabel = o["x_label"] || "",
yLabel = o["y_label"] || "",
isPercent = o["value_is_percent"],
precision = o["precision"] || 0;
var data = alamode.getDataFromQuery(queryName),
columns = alamode.getColumnsFromQuery(queryName),
xVals = _.uniq( _.map(data, xColumn) ),
yVals = _.uniq( _.map(data, yColumn) );
var uniqContainerClass = alamode.addContainerElement(htmlElement);
var color = d3.scale.quantize()
.domain(d3.extent(data, function(d) {
return Math.max(minValue, Math.min(maxValue, d[valueColumn]));
}))
.range(colors)
d3.select(uniqContainerClass)
.append("div")
.attr("class","mode-graphic-title")
.text(title)
d3.select(uniqContainerClass)
.append("div")
.attr("class","mode-simple-heatmap-label")
.text(yLabel)
headers = [xColumn].concat(yVals)
var table = d3.select(uniqContainerClass).append("table")
.attr("class","mode-simple-heatmap-table");
table.selectAll(".mode-simple-heatmap-table-header")
.data([0])
.enter().append("tr")
.attr("class","mode-simple-heatmap-table-header")
.selectAll("mode-simple-heatmap-table-header-cell")
.data(headers)
.enter().append("td")
.attr("class",function(d) {
if (isNaN(d)) { return "mode-simple-heatmap-table-header-cell heatmap-string"; }
else { return "mode-simple-heatmap-table-header-cell heatmap-number"; }
})
.text(function(d) { return d; })
table.selectAll(".mode-simple-heatmap-table-row")
.data(xVals)
.enter().append("tr")
.attr("class","mode-simple-heatmap-table-row")
.selectAll(".mode-simple-heatmap-table-cell")
.data(function(d) { return makeRow(data,d); })
.enter().append("td")
.style("background",function(d) { if (checkShade(d)) { return color(Math.max(minValue, Math.min(maxValue, d.value))); } })
.attr("class",function(d) { return cellClass(d); })
.text(function(d) { return fmt(d,o); })
function checkShade(entry) {
if (entry.value === "") {
return false;
} else if (entry.column == xColumn) {
return false;
} else if (entry.column == valueColumn) {
return true;
} else {
return false;
}
}
function cellClass(entry) {
var type = getDataType(entry.column);
if (type == "float" || type == "integer" || type == "number") {
return "heatmap-number";
} else {
return "heatmap-string";
}
}
function getDataType(column) {
return columns.filter(function(d) { return d.name == column })[0].type;
}
function makeRow(data,xVal) {
var row = [ {column: xColumn, value: xVal } ];
yVals.forEach(function(p) {
var matches = _.filter(data, function(d) {
return d[xColumn] == xVal && d[yColumn] == p
});
if (matches.length > 0) {
entry = d3.mean( _.map(matches,valueColumn) );
} else {
entry = minValue;
}
row = row.concat( {column: valueColumn, value: entry} )
})
return row;
}
function fmt(entry) {
var type = getDataType(entry.column);
var c = d3.format(","),
p = d3.format("." + precision + "%"),
t = d3.time.format("%b %d, %Y");
if (entry.value == "") {
return entry.value;
} else if (type == "datetime" || type == "timestamp" || type == "date") {
if (typeof moment == "function") {
return moment(entry.value).utc().format("ll")
} else {
return t(new Date(entry.value));
}
} else if (entry.column == valueColumn && isPercent) {
return p(entry.value);
} else if (entry.column == valueColumn) {
return c(entry.value);
} else {
return entry.value;
}
}
},
// A simple way to draw a heatmap on an existing table.
// It claculates averages automatically and supports multiple columns.
// Parameters:
// - queryToken: the name of the query that has the source data
// - vizId: table's id
// - columns: the columns to overlay a heatmap for as strings or objects of:
// - color_gradient: if present, overrides the default gradients. Should be an array of strings, where each value is a hex color string
// - inverse: if present, it reverses the color order (i.e. lower is better, higher is worse)
heatmapOverlay: function(o) {
var dataset = datasets.filter(function(data) { return data.query_token === o.queryToken })
var defaultColorGradients = [
// ["#d73027", "#f46d43", "#fdae61", "#fee08b", "#ffffbf", "#d9ef8b", "#a6d96a","#66bd63","#1a9850"],
['#E2EFD6', '#BCE0AF', '#8CCF8A', '#65BE76', '#41AC6D', '#1D9A6C', '#158B5E', '#0E7B50', '#096A42'],
['#D5F3D6', '#AFE7BD', '#89DAB0', '#64CDAD', '#40BEB4', '#1D9AAF', '#148C9E', '#0D7D8C', '#076D79'],
['#D2EFFF', '#A8DDFF', '#7ECAFF', '#54B5FF', '#2A9EFF', '#0086FF', '#0079DF', '#006BBF', '#005C9F']
]
// Used to convert rgb(x, x, x) color format from d3 to #hex format.
function componentFromStr(numStr, percent) {
var num = Math.max(0, parseInt(numStr, 10));
return percent ? Math.floor(255 * Math.min(100, num) / 100) : Math.min(255, num);
}
function rgbToHex(rgb) {
var rgbRegex = /^rgb\(\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*\)$/;
var result, r, g, b, hex = "";
if ((result = rgbRegex.exec(rgb))) {
r = componentFromStr(result[1], result[2]);
g = componentFromStr(result[3], result[4]);
b = componentFromStr(result[5], result[6]);
hex = "#" + (0x1000000 + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
return hex;
}
function heatmapColumnRules(columnData, dataset, valueFunc) {
var columnName = typeof columnData === 'string' ? columnData : columnData.name
var colors = columnData.color_gradient
if (columnData.inverse) {
colors = colors.reverse()
}
var avg = d3.mean(dataset.content.map(valueFunc));
var maxVal = d3.max(dataset.content.map(valueFunc));
var minVal = d3.min(dataset.content.map(valueFunc));
var buckets = d3.range(0, dataset.content.length)
var color = d3.scaleSequential()
.domain([minVal, maxVal])
.interpolator(d3.interpolateRgbBasis(colors));
var scale = d3.scaleThreshold()
.domain(buckets)
.range(dataset.content.map(valueFunc).sort())
return {
name: columnName,
rules: buckets.map(function (index) {
return {
type: '<=',
value: scale(index),
color: rgbToHex(color(scale(index)))
}
}).concat({
type: '>=',
value: maxVal,
color: colors[colors.length - 1]
})
}
}
alamode.customizeTable([{
vizId: o.vizId,
formatByColumn: {
columns: (o.columns || []).map(function (column, index) {
if (!column) throw new Error("Colum data isn't passed properly.");
var colName = typeof column === 'string' ? column : (column || {}).name
return heatmapColumnRules({
name: colName,
color_gradient: column.color_gradient || defaultColorGradients[index % defaultColorGradients.length],
inverse: column.inverse
}, dataset[0], function (row) { return row[colName] })
})
}
}])
},
// Built with Google Maps Javascript API
// https://developers.google.com/maps/documentation/javascript/
googleMap: function(o) {
var id = alamode.makeId(10);
var latColumn = o["lat_column"],
lngColumn = o["lng_column"],
queryName = o["query_name"],
apiKey = o["google_maps_api_key"],
// Optional
title = o["title"] || queryName,
labelColumn = o["label_column"],
htmlElement= o["html_element"] || "body",
centerLat = o["center_lat"] || 39.5,
centerLng = o["center_lng"] || -98.35,
zoom = o["starting_zoom"] || 4,
mapType = o["map_type"] || "terrain",
mapHeight = o["height"] || 600;
var data = alamode.getDataFromQuery(queryName);
var uniqContainerClass = alamode.addContainerElement(htmlElement);
d3.select(uniqContainerClass)
.append("div")
.attr("class","mode-graphic-title")
.text(title)
d3.select(uniqContainerClass)
.append("div")
.attr("class","mode-google-map")
.attr("id",id)
.style("height",mapHeight + "px")
jQuery.getScript("https://maps.googleapis.com/maps/api/js?key=" + apiKey, function() {
initMap()
function initMap() {
var myOptions = {
zoom: zoom,
center: new google.maps.LatLng(centerLat, centerLng),
mapTypeId: mapType
};
var map = new google.maps.Map(document.getElementById(id), myOptions );
data.forEach(function(d) {
var lat = d[latColumn],
lng = d[lngColumn];
if (labelColumn) {
label = d[labelColumn];
} else {
label = "";
}
var marker = new google.maps.Marker({
position: {lat:lat, lng:lng},
map: map,
title: label
})
var infowindow = new google.maps.InfoWindow({
content: label
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
});
}
})
},
// Built with Leaflet
// http://leaflet.github.io/Leaflet.heat/demo/
leafletMap: function(o) {
var id = alamode.makeId(10);
var latColumn = o["lat_column"],
lngColumn = o["lng_column"],
queryName = o["query_name"],
// Optional
title = o["title"] || queryName,
height = o["height"] || 400,
htmlElement= o["html_element"] || "body",
centerLat = o["center_lat"] || 39.5,
centerLng = o["center_lng"] || -98.35,
zoom = o["starting_zoom"] || 4,
dotRadius = o["dot_size"] || .4,
dotOpacity = o["dot_opacity"] || .8,
applyFilter = o["apply_filter"] || false;
var data = alamode.getDataFromQuery(queryName),
validData = [];
data.forEach(function(d) {
if (typeof d[latColumn] === "number" && typeof d[lngColumn] === "number") {
validData.push(d)
}
})
var uniqContainerClass = alamode.addContainerElement(htmlElement, applyFilter);
d3.select(uniqContainerClass)
.style("height",height + "px")
.append("div")
.attr("class","mode-graphic-title")
.text(title)
var mapHeight = height - $(uniqContainerClass + ".mode-graphic-title").height(),
mapWidth = $(uniqContainerClass).width();
d3.select(uniqContainerClass)
.append("div")
.attr("class","mode-leaflet-map")
.attr("id",id)
.style("height",mapHeight + "px")
.style("width",mapWidth + "px")
var baseLayer = L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18
});
var d = {
max: 8,
data: validData
};
var cfg = {
"radius": dotRadius,
"maxOpacity": dotOpacity,
"scaleRadius": true,
"useLocalExtrema": true,
"latField": latColumn,