Chart.js

Chart.js is a very light charting library for creating responsive charts using HTML/HTML5 canvas elements. In my opinion, this library is easier to use. You can read and download the Chart.js file at http://www.chartjs.org. You can download the Chart.js library at https://github.com/chartjs/Chart.js.

For the demo, we will develop a web application to visualize data using the Chart.js library. To show how to use the Chart.js in web application, we will use the same JSON data from the previous section to visualize the data. You can follow these steps to perform the demo:

  1. Create an HTML file, called chartjs.html. Then, put the Chart.js file and jQuery files into the HTML header:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chart.js Demo</title>
<script src="libs/Chart.js"></script>
<script src="libs/jquery-3.2.1.js"></script>
</head>
  1. To render a chart, we define the canvas on the HTML body. In this scenario, we define the width and height for our canvas as 200 and 100 pixels, respectively. We will generate a chart using JavaScript scripts:
<body>
<canvas id="myChart" width="200" height="100" style="border:1px solid #000000;"></canvas>
<script>
// generate a chart

</script>
</body>
</html>
  1. We use the Chart object with the line type. You can read about this API at http://www.chartjs.org/docs/latest/charts/line.html. The following is the implementation program to generate a chart:
$(document).ready(function() {
$.getJSON('data.json', function(data) {
console.log(data);
show_data(data);
});
});


function show_data(data){
var ctx = document.getElementById("myChart").getContext('2d');
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Sensor data',
borderColor: "rgba(210, 54, 54, 1)",
fill: false,
data: data
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
}
}
});
}
  1. Save this file. Then, run that HTML file into your web server. You can see my chart program in the following screenshot:

We have learned how to work with the Chart.js library to visualize data on a web application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.134.154