Change Step Area Color Based on Value - Javascript Chart.js

Javascript examples for Chart.js:Chart Color

Description

Change Step Area Color Based on Value

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){// w ww .  ja  v  a  2  s . com
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;
                    })
                })
            })
    }
});
var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            // 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)" },
            ],
            data: [25, 49, 50, 75, 100, 125, 150]
        },
                {
                    label: "My Second dataset",
                    fillColor: [
                        { to: 50, fillColor: "rgba(220,220,220,1)" },
                        { from: 50, to: 75, fillColor: "rgba(220,0,0,1)" },
                        { from: 75, to: 100, fillColor: "rgba(0,220,0,1)" },
                        { from: 100, fillColor: "rgba(0,0,220,1)" },
                    ],
                    data: [25, 49, 50, 75, 100, 125, 150]
                }
    ]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx).BarAlt(data);
    }

      </script> 
   </head> 
   <body> 
      <canvas id="myChart"></canvas>  
   </body>
</html>

Related Tutorials