我希望能够根据我的数据表搜索和/或排序的变化来显示我的图表,如本示例中使用高图显示的那样
使用Highcharts.js的数据可视化DataTables.js。
<a href="https://codepen.io/tutsplus/pen/GMVapQ">
<div class="container">
<table id="dt-table">
<thead>
<tr>
<th>Country</th>
<th>Population (2017)</th>
<th>Density (P/Km²)</th>
<th>Med. Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>China</td>
<td>1,409,517,397</td>
<td>150 </td>
<td>37</td>
</tr> more code on site ....
我目前正在使用mdbootstrap,PHP,MySQL,数据表。
是否有可能使用chart.js达到相同的结果,如果有的话,还有任何编码示例,或者我应该通过将highcharts编码更改为chart.js来将此codepen示例用作我的chart.js可视化的起点。等效。
非常感谢。
科林
$(document).on('dblclick', '.dataTable td', function () {
let index = $(this).index();
let col = $(this).closest('.dataTable').DataTable().columns(index).data()[0].sort();
let groups = col.groupBy(function (v) {
return v;
});
var config = {
type: 'pie',
data: {
datasets: [{
data: groups.map(x => x.group.length),
backgroundColor: groups.map(x => getRGBAColorFromString(x.group[0])),
label: "pie"
}],
labels: groups.map(x => x.group[0])
},
options: {
responsive: true
}
};
//display you chart here
//....
let ctx = document.getElementById('canvasId').getContext('2d');
window.myPie = new Chart(ctx, config);
});
注意,绘制图表所用的元素必须是画布。另外,我使用了'dblclick'事件,根据您自己的需要进行更改。
js中的groupBy代码看起来像这样:
Array.prototype.groupBy = function (hash) { var _hash = hash ? hash : function (o) { return o; }; var _map = {}; var put = function (map, key, value) { if (!map[_hash(key)]) { map[_hash(key)] = {}; map[_hash(key)].group = []; map[_hash(key)].key = key; } map[_hash(key)].group.push(value); } this.map(function (obj) { put(_map, obj, obj); }); return Object.keys(_map).map(function (key) { return { key: _map[key].key, group: _map[key].group }; }); }
可能想要使用类似的颜色作为颜色。可以更改逻辑(要在我们的应用上仅产生鲜艳的颜色,因此是%67和+189)]
function getRGBAColorFromString(s) {
if (!s) return "#fff";
let sum = 0;
for (i = 0; i < s.length; i++) {
sum += s.charCodeAt(i);
}
let r = sum * 31 % 67;
let g = sum * 17 % 67;
let b = sum * 51 % 67;
return "rgba(" + (r + 189) + "," + (g + 189) + "," + (b + 189) + ", 1)";
}
希望对您有所帮助:D
欢呼声