Parse an object to column chart - Javascript Chart.js

Javascript examples for Chart.js:Column Chart

Description

Parse an object to column chart

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.2.1/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//from w w w .  j a v a2s . com
var obj = {
    "and": 2,
    "two": 1,
    "too": 1,
    "mother": 2
};
var ctx = document.getElementById("myChart");
var data = {
   labels: [],
    datasets: [{
        label: "My dataset",
        backgroundColor: "rgba(75,192,192,0.4)",
        borderColor: "rgba(75,192,192,1)",
        data: []
    }]
};
Chart.pluginService.register({
    beforeInit: function(chart) {
        var data = chart.config.data;
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
               data.labels.push(key);
                data.datasets[0].data.push(obj[key]);
            }
        }
    }
});
var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
    }

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

Related Tutorials