Chartjs-Data Visualization DataTables.js using chart.js

0👍

I did something like this with a pie chart, to show value division in a single column. i think you can easily edit it to use other graph types, altough there isn’t a perfect symmetry between graphs and tables.

$(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);
});

Notice that the element in which you draw the chart must be a canvas.
also, i used the ‘dblclick’ event, change it according to your own needs.

groupBy code in js looks something like that:

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 };
    });
}

Might wanna use something like that for the colors. can change the logic (it’s ment to produce only bright colors on our app, hence the %67 and the +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)";
}

hope this helps:D

cheers

Leave a comment