Build data stories using modern charting libraries - Part1
Create automated and responsive visualizations directly in your website/blog
So far in all our blogs, we have focused on getting business users familiar with presenting their data analysis on web using no-code visualization tools. While no-code tools such as PowerBI or Tableau create great visualizations and are easy to use, they still have some limitations such as below:
If we use the free versions of the products, our underlying data is made public and the licensing costs for the paid versions are not always justified.
Embedding content created on these platforms onto your website may need specialist support and may not always be economical.
When the data source is in JSON format, some of these tools are not plug and play. The data needs to be converted to a tabular format (as we have seen in Blog 2 ) that these tools can then consume.
In this blog we will introduce our readers to JavaScript charting libraries, many of which are free to use and yet feature rich to cover wide range of charts and formats. Moreover these being pure visualization libraries, it is easy to integrate them with any technology platform.
Although the name JavaScript may put off non-technical users, by the end our blog even a non-technical user will lose inhibitions in using them.
Note: For our demo we are using Chart.js, however there are several others. One may search the web for JS Charting libraries and find a whole of lot material for the specific needs.
So let us see how we can achieve this in three easy steps.
Step 1 - Create a static visualization by adding the data manually
In our PowerBI example , we created our chart on PowerBI cloud, generated an embed code and copied the link in an iFrame on our site. In this example, we will create the chart directly on our site. Let us see how we can do that in four easy steps.
Copy the below text and create a text file and save it as '.html' instead of '.txt'. We have created a blank html page. Now if you open the file, it will show a blank page on your browser.
<!doctype html> <head> </head> <body> </body> </html>
Make sure you add a .html to file name and Save as type All Files as show below:
Now right click and edit the file in any text editor or notepad. Let us first add the canvas (the html element used to draw grahics on web page) in which we will show the chart. We have to include the below line in between the <body> </body> tags
<!doctype html> <head> </head> <body> <canvas id="myChart"></canvas> </body> </html>
Now if you open the file in browser, the page is still blank because the content for the "myChart" is not defined yet.
Before we can use Chart.js, we have to include it in our page. For that let us add the below line in between the <head> </head> tags as shown below.
Note: Depending on your technology infrastructure, there are multiple ways to install Chart.js. Refer documentation for other methods to install Chart.js
<!doctype html> <head> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> </head> <body> <canvas id="myChart"></canvas> </body> </html>
We can now create a chart. Let us copy the chart config from the Chart.js documentation. Th page has good explanation on what each line in the code below means. We have to paste the code in the body tag as shown below. Proceed to next steps to add our data and then our chart is ready.
<!doctype html> <head> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> </head> <body> <canvas id="myChart"></canvas> <script> var ctx = document.getElementById('myChart'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'] , datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3] , backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); </script> </body> </html>
All we did was update the three tags as show below and include the code in our example in chart1 and the first chart in our demo was ready. We can further format our charts by changing fonts, colours or other formatting options. Chart.js documentation has several samples which we can directly download and reuse.
Step 2 - Integrate your visualization on your web page/blog
Note: Step 2 and Step 3 can be somewhat technical for a business user. We recommend taking technical support from your technology team if you face issues in executing Step 2 and Step 3.
Include Chart.js in your existing scripts section. For example we have included it as shown below:
We can now embed Chart.js charts. In our demo, we have created a new html block for chart as shown below. The id="myChart", uniquely identifies our chart element and we will reference this chart in our scripts section.
Next copy the chart config we created in Step 1 in between <script> and </script> tags either as a new <script> and </script> in your web page or you can create a new file and reference it here. Your chart is now integrated on your page.
Step 3 - Keep your visualization updated by sourcing data in real-time
Note: Step 2 and Step 3 can be somewhat technical for a business user. We recommend taking technical support from your technology team if you face issues in executing Step 2 and Step 3.
Let us use a sample API to source data directly into our chart. We will use jQuery AJAX method to source data in our example. In our context of creating interactive data stories AJAX helps in getting the data and jQuery simplifies the process by providing easy to use methods for the same.
Note: While these terms may sound technical, as an end user or content creator we only need to know how to use them. In the below example we will show how easy it is to use ajax and automatically source data into our visualizations.
Let us first make our chart dynamic by replacing the highlighted labels and data values in the script we defined in Case1 by empty arrays. Now if you run the chart it will be blank. In subsequent steps will see how to get data in the highlighted row and column variables.
var ctx = document.getElementById('myChart'); var column = [] var row = [] var myChart = new Chart(ctx, { type: 'bar', data: { labels: row , datasets: [{ label: '# of Votes', data: column ,
Next let us add the part to source data. In order to use jQuery AJAX we have to include CDN for jQuery similar to what we did for Chart.js in our scripts section as shown below.
Next we have to add the below part to the script we wrote in static chart. This is a JavaScript function. We are intentionally skipping the technical explanation of the syntax so that non-technical users can understand the usage. We need to update each highlighted part as shown below.
var GetChartData = function () { $.ajax({ url: "https://api.indiadatahub.com /v1/data?id=MOINHPCHEN11Q&fields=India &api_key=testing", method: 'GET', dataType: 'json' , success: function (d) { d.dataset[0].data.slice().reverse(). forEach(function(row) { column.push(row.India) label.push(row.Date.toString()) }); } }); respondCanvas(); };
Now let us look at what each of the highlighted parts indicate.
url : The link for the API. The API provider will share the link and the usage. For example here we are using an API that IndiaDataHub provides to its customers.
method : The allowed HTTP method to use for the request (e.g. "POST", "GET", "PUT"). This is also given by API provider. In our example we are using GET Method.
dataType : The type of data that you're expecting in result. Here we are getting data in JSON format so we have updated it as 'json'.
success: The success block defines what we should do with the data we get from the API. In the above example, we are processing each row and pushing the y-axis value in the empty column we declared in step1 and x-axis value in empty label we declared.
respondCanvas() : Now that we have the data in the format we want, we are now calling the respondCanvas() function we will define in next step to load our chart in real-time.
Now let us define the respondCanvas() function by moving the chart config inside the opening and closing curly braces { } of the function as shown below:
function respondCanvas() { var c = $('#myChart'); var ctx = document.getElementById('myChart'); var chart = new Chart(ctx, { type: 'bar', data: { labels: label, datasets: [{ label: 'House Price Index - Chennai', data: column, }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); }
When we are getting data in real-time, the website from which we are sourcing data generally takes time to respond. Let us now add a timeout function to to our script block to delay loading the block by say 500 milliseconds as shown below. We can change this time depending on the time it takes for your chart to load data.
$(document).ready(function() { $(window).resize(setTimeout(respondCanvas, 500)); GetChartData(); });
In four steps we have created a data visualization which auto-updates every time someone views the page. The entire code would now look as follows:
<canvas id="myChart" width="400" height="400"></canvas>
<script>
//Declare the chart
var c = $('#myChart');
var ctx = c.get(0).getContext("2d");
var container = c.parent();
var $container = $(container);
c.attr('width', $container.width()); //max width
c.attr('height', $container.height()); //max height
//Define the chart config
function respondCanvas() {
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: label,
datasets: [{
label: 'House Price Index - Chennai',
data: column
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
//Get the chart data
var GetChartData = function () {
$.ajax({
url: "https://api.indiadatahub.com
/v1/data?id=MOINHPCHEN11Q&fields=India
&api_key=testing",
method: 'GET',
dataType: 'json' ,
success: function (d) {
d.dataset[0].data.slice().reverse().
forEach(function(row) {
column.push(row.India)
label.push(row.Date.toString())
});
}
});
respondCanvas();
};
//Make the chart responsive
$(document).ready(function() {
$(window).resize(setTimeout(respondCanvas, 500));
GetChartData();
});
</script>
In conclusion, the JS charting libraries are better suited and offer a lot more flexibility and customization compared to no-code visualization tools in the following scenarios:
When the reports/dashboards are required to be displayed on a public website or in an internal company or client web portal, it is a lot easier to simply include the config for a JS chart in the code for the user interface as compared to using separate tools for creating visualization and then embedding them in the site.
As we have seen in our examples, the JS charting libraries directly consume data in JSON format. When the data is provided in JavaScript compatible format, which is the case with most API's, JS charts save the need for converting data into a different format.
By using technologies such as jQuery and AJAX we can easily keep our content updated in real-time with out any additional linking or automation.
JS Charting libraries are also more suitable with underlying report or dashboards layout is more or less fixed from week to week or month to month as in that case the need to touch the code is minimized.
However there is still one issue with the above approach. Our API call is made public because anyone from their browsers can access our private API key. Generally technology teams protect our data and keys by creating a backend. You no longer need to be a technology expert to create a backend. The Part 2 of this blog will cover how we can achieve this objective by using cloud technologies.