[Chartjs]-Chart.js draw mathematical function

28👍

✅

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

Leave a comment