<div id="chart"></div>
That small code snippet produces such a beautiful chart with a tooltip:
But as you can see, the data in the tooltip are not sorted. The goal of this post is to show how to sort it.
Unfortunately, there is no a simple option to achieve this. We have to override whole the tooltip code for that. The key property here is contents. It allows to use a custom template for tooltip appearance
Awesome! Tooltip items are sorted now. But what if we want to sort the items values ascend? We have to add the following sort function:
d.sort(function(a, b){
return a.value - b.value;
});
The entire contents:
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 = "" + (title || title === 0 ? "" : "");
}
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 += "";
text += "";
text += "";
text += "";
}
return text + "| " + title + " | |
|---|---|
| " + name + " | " + value + " |
You can try it on the JSFiddler:
https://jsfiddle.net/AndrewBuntsev/abqt8zgh
No comments:
Post a Comment