C3 chart sorted tooltip
by AndrewBuntsev
HTML
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script src="https://unpkg.com/c3@0.6.8/c3.js"></script>
<link rel="stylesheet" href="https://unpkg.com/c3@0.6.8/c3.css"/>
</head>
<body>
<div id="chartC3"></div>
</body>
</html>
JavaScript
var chart = c3.generate({
bindto: '#chartC3',
data: {
columns: [
['data1', 30, 200, 100, 400, 250],
['data2', 50, 20, 10, 40, 25],
['data3', 150, 10, 40, 40, 15],
['data4', 80, 40, 70, 20, 45],
['data5', 30, 60, 35, 90, 40]
]},
tooltip: {
contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
var $$ = this, config = $$.config,
titleFormat = config.tooltip_format_title || defaultTitleFormat,
nameFormat = config.tooltip_format_name || function (name) { return name; },
valueFormat = config.tooltip_format_value || defaultValueFormat,
text, i, title, value, name, bgcolor;
d.sort(function(a, b){
return a.value - b.value;
});
for (i = 0; i < d.length; i++) {
if (!(d[i] && (d[i].value || d[i].value === 0))) { continue; }
if (!text) {
title = titleFormat ? titleFormat(d[i].x) : d[i].x;
text = "<table class='" + $$.CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : "");
}
name = nameFormat(d[i].name);
value = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index);
bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);
text += "<tr class='" + $$.CLASS.tooltipName + "-" + d[i].id + "'>";
text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>";
text += "<td class='value'>" + value + "</td>";
text += "</tr>";
}
return text + "</table>";
}
}
});