Create bar chart width json data - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Create bar chart width json data

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  .j a  v a2s.  com
//Grabbing the canvas context.
var ctx = document.getElementById("myChart").getContext("2d");
// Serialized version of your json object
var json = [{"title":"Tweets","y_axis_label":"Number of Tweets","x_axis_labels":["12AM-06AM","06AM-12PM","12PM-06PM","06PM-12AM"],"series":[{"name":"Tweets","data":[8,1,2,0]},{"name":"Retweets","data":[8679,4692,2105,0]},{"name":"Replies","data":[3427,789,1391,0]},{"name":"Quotes","data":[284,66,73,0]},{"name":"Favorites","data":[0,0,0,0]}]},{"title":"Tweets","y_axis_label":"Number of Tweets","x_axis_labels":["12AM-06AM","06AM-12PM","12PM-06PM","06PM-12AM"],"series":[{"name":"Tweets","data":[8,1,2,0]}]},{"title":"Retweets","y_axis_label":"Number of Tweets","x_axis_labels":["12AM-06AM","06AM-12PM","12PM-06PM","06PM-12AM"],"series":[{"name":"Retweets","data":[8679,4692,2105,0]}]},{"title":"Replies","y_axis_label":"Number of Tweets","x_axis_labels":["12AM-06AM","06AM-12PM","12PM-06PM","06PM-12AM"],"series":[{"name":"Replies","data":[3427,789,1391,0]}]},{"title":"Quoted Tweets","y_axis_label":"Number of Tweets","x_axis_labels":["12AM-06AM","06AM-12PM","12PM-06PM","06PM-12AM"],"series":[{"name":"Quotes","data":[284,66,73,0]}]},{"title":"Favorites","y_axis_label":"Number of Tweets","x_axis_labels":["12AM-06AM","06AM-12PM","12PM-06PM","06PM-12AM"],"series":[{"name":"Favorites","data":[0,0,0,0]}]}];
// You can add options to this mapedData as required.
var mapedData = [];
//I am displaying the bar graph for first dataset which is based on zero index you need to apply map or reducer if you want to combine data into one graph.
json[0].series.forEach(function(set){
 mapedData.push({label: set.name, data: set.data})
});
var data = {
    labels: json[0]["x_axis_labels"],
    datasets: mapedData
};
var myBarChart = new Chart(ctx).Bar(data);
    }

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

Related Tutorials