score:24

Accepted answer

using chart.js plugins can help you doing it quite easily. a plugin lets you handle some events triggered through the chart creation such as the initialization, the resize, etc.

chart.pluginservice.register({
    beforeinit: function(chart) {
        // all the code added here will be executed before the chart initialization
    }
});


i'll add a plugin which could be useful for your problem, but first let me explain how it works.

first, you'd need to add a new attribute to your datasets, named function. its value must be a function with one argument and a returned value :

var data = {
    labels: [1, 2, 3, 4, 5],
    datasets: [{
        label: "f(x) = x", // name it as you want
        function: function(x) { return x },
        data: [], // don't forget to add an empty data array, or else it will break
        bordercolor: "rgba(75, 192, 192, 1)",
        fill: false
    },
    {
        label: "f(x) = x²",
        function: function(x) { return x*x },
        data: [],
        bordercolor: "rgba(153, 102, 255, 1)",
        fill: false
    }]
}

now you have to add the following plugin before you call new chart() (to create your chart) or else it won't be added into the chart's plugin service :

chart.pluginservice.register({
    beforeinit: function(chart) {
        // we get the chart data
        var data = chart.config.data;

        // for every dataset ...
        for (var i = 0; i < data.datasets.length; i++) {

            // for every label ...
            for (var j = 0; j < data.labels.length; j++) {

                // we get the dataset's function and calculate the value
                var fct = data.datasets[i].function,
                    x = data.labels[j],
                    y = fct(x);
                // then we add the value to the dataset data
                data.datasets[i].data.push(y);
            }
        }
    }
});

you can now freely create your chart with the options you need.


follows the result of a fully working example which you can find on this jsfiddle :

enter image description here


Related Query

More Query from same tag