Change Step Area Color Based on Value

๐Ÿ‘:0

You can extend the Chart.js bar chart (~ step area chart) to do this, like so

Chart.types.Bar.extend({
    name: "BarAlt",
    initialize: function (data) {
        Chart.types.Bar.prototype.initialize.apply(this, arguments);

        this.datasets
            .filter(function (dataset) {
                // only do this for the arrays
                return typeof (dataset.fillColor) === "object";
            })
            .forEach(function (dataset) {
                dataset.bars.forEach(function (bar) {
                    dataset.fillColor.forEach(function (range) {
                        if (bar.value >= (range.from || -Infinity) && bar.value < (range.to || Infinity))
                            // set the bar color, the tooltip hover color and the cached (used to restore after a tooltip hover) color based on the value
                            bar.fillColor = bar.highlightFill = bar._saved.fillColor = range.fillColor;
                    })
                })
            })
    }
});

where the chart data has an array (instead of a string) for fillColor, like so

datasets: [
    {
        ...
        // sorted range with colors
        fillColor: [
            { to: 50, fillColor: "rgba(220,220,220,0.2)" },
            { from: 50, to: 75, fillColor: "rgba(220,0,0,0.2)" },
            { from: 75, to: 100, fillColor: "rgba(0,0,220,0.5)" },
            { from: 100, fillColor: "rgba(0,0,220,0.2)" },
        ],
        ...

Remember to call the chart using BarAlt instead of Bar


Fiddle โ€“ https://jsfiddle.net/hhybyhfw/


enter image description here

Leave a comment