Hi everyone, I hope you all are doing great. I'm back with another blog in which we are going to focus on Data Visualization.
Table Of Content
- What is Data Visualization?
- Why should you adopt it?
- What are different options available?
- Why I'm going to use Chartjs in this tutorial?
- Example
- Additionals
- Conclusion
What is Data Visualization or Data Viz. ?
In simple terms data viz. is nothing but a process of representing your boring data in an attractive way using charts, graphs, and other forms of visual representations. The main purpose of using data visualization is to study the trends, results, and other things which will help you in better decision making.
Why should you adopt it?
- Data Viz makes it easy to feed the data to end-users which excites their mind.
- It gives an attractive design aspect to your applications.
- Data viz makes it easier to understand the data.
- It adds an extra bit of interactivity to your applications as well.
What are different options available?
Why I'm going to use Chartjs in this tutorial?
Chartjs has many options when it comes to types of charts. Following are the types of charts that Chartjs provides.
- Doughnut and Pie Chart
- Line Chart
- Bar Chart
- Radar Chart
- Bubble Chart and more.
Along with that, you have different plugins, animations, etc features available in Chartjs.
Example
In this example, we are going to represent the monthly expense of a user across different categories in the form of a doughnut or a pie chart.
Let's get started
1. Create a new project folder
2. Create 3 Files, index.html, style.css, and app.js
3. Now open your favorite text editor.
Your Project Structure should look like this
- Now, we have two ways to integrate chartjs in our project that are via npm or using CDN
We will be going with the CDN method. So, grab your CDN link here.
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.5.1/dist/chart.min.js"></script>
Chartjs actually need the HTML5's canvas element to render our charts on the page. (Canvas element is used to render 2D shapes dynamically).
So let's add the canvas element in our index.html file.
<div>
<canvas id="myChart" width="500" height="500"></canvas>
</div>
Finally, your index.html should look like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>Data Viz.</title>
</head>
<body>
<div>
<canvas id="myChart" width="500" height="500"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.5.1/dist/chart.min.js"></script>
<script src="./app.js"></script>
</body>
</html>
style.css
body {
min-height: 100vh;
display: grid;
place-items: center;
}
We don't need much of the stylings here. The above code will help us to center our chart on the webpage that pretty much it as far as CSS is concerned.
Now let's come to the nitty-gritty part ๐
In app.js
let ctx = document.getElementById("myChart").getContext("2d");
This line will help us to grab our canvas element in javascript.
Now, Let's grab some colors that we want to use in our doughnut chart
let backgroundColor = [
"rgba(18, 176, 232,1)",
"rgba(56, 204, 119,1)",
"rgba(244, 190, 44,1)",
"rgba(106, 27, 77,1)",
"rgba(153, 102, 255, 1)",
];
let borderColor = [
"rgba(18, 176, 232,1)",
"rgba(56, 204, 119,1)",
"rgba(244, 190, 44,1)",
"rgba(106, 27, 77,1)",
"rgba(153, 102, 255, 1)",
];
- To represent the data in visual forms we need data right? Yes, so let's have an array of our monthly expenses.
let monthlyExpenses = [1000, 200, 400, 100, 50];
As you can see we have an array of monthly expenses but it doesn't make any sense without telling what each expense is for right? So, let's define labels corresponding to each of our monthly expenses.
let labels = ["Rent", "Mobile Bills", "Coffe & Pizza", "Courses", "Travel"];
Since we have got all the ingredients now. Let's ready our dish now ๐
let myChart = new Chart(ctx, {
type: "doughnut",
data: {
labels: labels,
datasets: [
{
data: monthlyExpenses,
backgroundColor: backgroundColor,
borderColor: borderColor,
borderWidth: 1,
},
],
},
});
Here we have created a new instance of chart using new Chart which accepts two arguments context and options. Context (ctx) is nothing but our canvas in 2D context here. we are assigning it to a variable called myChart.
Let's have a deep look at the second argument of new Chart which is options.
type: type accepts a string value for the type of chart you want. In our case, we wanted a doughnut so we have assigned "doughnut" as the value. Similarly, if you want a bar chart you can assign "bar" as a value to the type (ie. type: "bar").
data: data objects contains the main parts of our data visualization,
- labels: it accepts the labels array. These labels will be shown as legends in our chart.
- datasets: it accepts an array of objects. Let's see each key-value pair in this object.
a. data: it needs an array of values which we need to visualize on our chart. In our case, we want to visualize the monthly expenses so we have assigned monthlyexpenses array to it.
b. backgroundColor: backgroundColor needs an array of different color strings which you want to use to represent the sectors/tracks of the doughnut chart.
c. borderColor: borderColor needs an array of different color strings which you want to use as the border of each sector/track of the doughnut chart.
d. borderWidth: This needs a numerical value to define the thickness of the border.
After writing the above code in your app.js file. It should look like this
app.js
let ctx = document.getElementById("myChart").getContext("2d");
let backgroundColor = [
"rgba(18, 176, 232,1)",
"rgba(56, 204, 119,1)",
"rgba(244, 190, 44,1)",
"rgba(106, 27, 77,1)",
"rgba(153, 102, 255, 1)",
];
let borderColor = [
"rgba(18, 176, 232,1)",
"rgba(56, 204, 119,1)",
"rgba(244, 190, 44,1)",
"rgba(106, 27, 77,1)",
"rgba(153, 102, 255, 1)",
];
let monthlyExpenses = [1000, 200, 400, 100, 50];
let labels = ["Rent", "Mobile Bills", "Coffe & Pizza", "Courses", "Travel"];
let myChart = new Chart(ctx, {
type: "doughnut",
data: {
labels: labels,
datasets: [
{
data: monthlyExpenses,
backgroundColor: backgroundColor,
borderColor: borderColor,
borderWidth: 1,
},
],
},
});
Your chart will look like this
Additionals
Let's say we want to position those legends at the bottom instead of the top. For that let's do the following.
Add the options in your data object
let myChart = new Chart(ctx, {
type: "doughnut",
data: {
labels: labels,
datasets: [
{
data: monthlyExpenses,
backgroundColor: backgroundColor,
borderColor: borderColor,
borderWidth: 1,
},
],
},
options: {
plugins: {
legend: {
position: "bottom",
},
},
},
});
Now, our legends are visible at the bottom of our chart.
You can play around with these options to get more control of your charts. I would encourage you guys to go through the documentation of chartjs to check out more options.
Let's say we want to add update the chart or rerender the chart
In order to do so we have various methods available such as destroy() , update() etc.
It is important to use any of them if you want to re-render the chart otherwise you will have an error. Let's see how can we update the chart on button click.
Add a button in your index.html
<button>Update</button>
Update your style.css and add the following code
button {
background-color: rebeccapurple;
padding: 1rem 1.5rem;
color: white;
font-family: sans-serif;
border-radius: 12px;
outline: none;
border: none;
cursor: pointer;
}
Now is app.js
let btn = document.querySelector("button");
function updateData(chart) {
monthlyExpenses = [2000, 400, 800, 200, 100];
backgroundColor = ["#FF6263", "#383CC1", "#38CC77", "#AF9D5A", "#E03B8B"];
borderColor = ["#FF6263", "#383CC1", "#38CC77", "#AF9D5A", "#E03B8B"];
borderWidth = 1;
chart.data.datasets.pop();
chart.data.datasets.push({
data: monthlyExpenses,
backgroundColor,
borderColor,
borderWidth,
});
chart.update();
}
btn.addEventListener("click", (e) => {
updateData(myChart);
});
As we can see that we are updating the values of our monthlyExpenses, backgroundColor, borderColor array along with borderWidth.
then we are taking the chart and using the pop method removing everything from the datasets of the existing chart and populating it with our new values using the push() method of the array. Then we are calling chart.update() it will update our chart and we won't face any errors.
Final output after clicking update button
Conclusion
In this blog, we have talked about data viz and its importance. Along with different options available to implement the data viz. Finally, we have implemented a doughnut chart using Chartjs and JavaScript.
I hope I was able to deliver something good to you guys โบ. Feedbacks, suggestions, etc are always welcomed.
Have a fun and safe time and Thank you so much for dedicating your time to go through this blog โค
Let's Learn and Grow Together. Adios amigos/amigas hasta la proxima vez ๐โ