Charts.js Data Index based on selected datasets - Javascript Chart.js

Javascript examples for Chart.js:Chart Data

Description

Charts.js Data Index based on selected datasets

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/2.1.6/Chart.bundle.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*  w w  w  . jav a2s.  c om*/
 var paitentData = {
    labels: ["Today", "Week", "Month", "Year"],
    datasets: [{
       label: "Hospital Patients",
       fillColor: "#79D1CF",
       strokeColor: "#79D1CF",
       data: [24, 20, 30, 40], 
       hidden: true, 
    }, {
       label: "Referral Patients",
       fillColor: "#79D1CF",
       strokeColor: "#79D1CF",
       data: [14, 24, 34, 44] 
    }, {
       label: "Total Patients",
       fillColor: "#79D1CF",
       strokeColor: "#79D1CF",
       data: [22, 32, 43, 52] 
    }]
 };
 var opt = {
    responsive: true,
    legend: {
       position: 'top',
    },
    title: {
       display: true,
       text: 'Patients Graph'
    },
    hover: {
       animationDuration: 1
    },
    animation: {
       duration: 1,
       onComplete: function() {
          var chartInstance = this.chart,
             ctx = chartInstance.ctx;
          ctx.textAlign = 'center';
          ctx.fillStyle = "rgba(0, 0, 0, 1)";
          ctx.textBaseline = 'bottom';
          this.data.datasets.forEach(function(dataset, i) {
             var isDatasetVisible = chartInstance.controller.isDatasetVisible(i); // true/false
             if (!isDatasetVisible) 
                return; 
             var meta = chartInstance.controller.getDatasetMeta(i);
             meta.data.forEach(function(bar, index) {
                var data = dataset.data[index];
                ctx.fillText(data, bar._model.x, bar._model.y - 5);
             });
          });
       }
    }
 };
 var ctx = document.getElementById("patientsBarGraph").getContext("2d"); // getting the id of canvas
 var MyNewChart = new Chart(ctx, {
    type: 'bar',
    data: paitentData,
    options: opt
 });
    }

      </script> 
   </head> 
   <body> 
      <div id="patientsBarGraphDiv" style="border: 1px solid black"> 
         <canvas id="patientsBarGraph"></canvas> 
      </div>  
   </body>
</html>

Related Tutorials