A Comprehensive Guide to Data Visualization with Chart.js

What is Chart.js?

There are many libraries out there that can help you visualize some data in your blog posts or presentations. One of the libraries you can use is Chart.js. Chart.js was created in 2013 by his London-based web developer Nick Downie. It is maintained by his second most popular JS charting library on GitHub. Chart.js is a free, open-source JavaScript library that is freely available to all users and helps plot data in web applications.

Chart.js supports the 8 chart types which are

  1. Bar
  2. Line
  3. Area
  4. Pie
  5. Bubble
  6. Radar
  7. Scatter

Here is an example of a Bar Chart that is created using Chart.js:

Chart.js Bar chart according to months

Chart.js can be used with the HTML5 Canvas element. Canvas is an element that provides a simple and powerful way to draw graphics using JavaScript. You can use it to draw diagrams, create photo compositions, and create simple animations. The Chart.js website has a lot of documentation with basic information on how to create a simple chart.

Chart.js can be used with plain JavaScript or various module loaders. You don’t have to be a JavaScript expert to use Chart.js to create different types of charts to present your data in great ways. With a little JavaScript and HTML, you can create charts in no time. Chart.js is rendered using the Canvas element which is supported by all browsers.

Installation:

Import the link of the latest version inside the script tag

https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.1.1/chart.min.js

OR

You can also install Chart.js by using NPM

Copy and paste the command below to download it into your project:

npm install chart.js --save

You can set up your project with CodePen or use a text editor like VSCode.

Create a simple index.html file and load the CDN in the body section. We will also create a script.js file in which we will later add code to create charts using Chart.js.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Chart.js beginners guide</title>
<link rel="stylesheet" href="style.css">
</head>
<body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.1.1/Chart.min.js"></script>
<script src="script.js"></script>
</body>
</html>

Now that we’ve included Chart.js in our project, we can move on to creating a place to render the chart.

Create a canvas tag inside the body tag:

<canvas id="myChart" width="800" height="400"></canvas>

The ID is very important and you can name it whatever you like, but it’s best to use a meaningful name that represents the type of chart you’re rendering.

The body tag now should look like this

<body>
<canvas id="myChart" width="800" height="400"></canvas> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.1.1/Chart.min.js"></script>
<script src="script.js"></script>
</body>

Now let’s prepare data for the graph which we want to show

Month (x-axis)Data (y-axis)
January

February

March

April

May

June

July

83

51

95

94

61

29

46

We are integrating a graph for data which have shown in the figure above

Now create a script.js file, open it and write the code given below

var data= [83, 51, 95, 94, 61,29,46];
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];

As you can see, each Month in the Months variable corresponds to the number of the value data variable. The accuracy of figures depends on this.

Now to create a bar chart write the corresponding code on top of your script.js file

var ctx = document.getElementById("myChart");

This code gets the canvas element from the HTML with the id chart1 and stores it in the variable ctx.

Variables can have any name. ctx is just convection that most programmers like and use it.

Now let’s create the chart. To create a chart, we first need to create an instance of Chart().

To create an instance, we need to call new Chart(), so enter the following code:

var myChart = new Chart(ctx, {
type: 'bar',
data: {}
}
)

The new Chart() object accepts the following arguments.
ctx is the variable used to store the canvas element. A
configuration object that allows you to set the chart type, data, and chart options.

The configuration object looks like this:

{
type: 'bar',
data: {},
options: {} // optional
}

Here are the property descriptions:

Type: ‘Bar’: Allows you to specify the graph to create. In this example, we will create a bar chart. If you want a pie or line chart, you can specify it as type: ‘pie’ or type: ‘line’.

Data: Contains the data (labels, datasets) used to draw the graph.

Options: Contains configuration options to customize the chart. Such as changing the position of the legend, enable/disable responsiveness, controlling styles, etc.

The code hasn’t rendered the chart yet, so in order to render the chart, we need to add some data (see next Save it in the framework and star saved in a data object like

var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: months,
datasets: [{
label: 'Products sold monthly',
data: data
}]
},
});

Your script.js should look like this now

var ctx = document.getElementById("myChart");

var data= [83, 51, 95, 94, 61,29,46];
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];

var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: months,
datasets: [{
label: 'Products sold monthly',
data: data
}]
},
});

Now open your index.html file with Chrome or any other browser and you should now see a bar chart(Same as the first figure).

Unleash The Power of Data Visualization: Transforming Information into Action!

What are Datasets?

And now to understand datasets let me show you what happened here

datasets: [{
label: 'Products sold monthly',
data: data
}]

The data property object has two properties labels and datasets.

Labels take an array (months) and display each element as a label on the x-axis.

Datasets take an array of objects with the following properties:

➡️ label: The label property takes a string. It appears on top of the chart or when the cursor hovers over the bars.

➡️ data: Data takes an array of values(Months) and displays the data on the y-axis(vertically).

Control Chart.js with Height and Width

Before we can style the bar, there is an issue that needs to be fixed. This is primarily for people who want to test their code and view charts in their browsers.

You may notice that the browser displays the chart in full-screen mode and does not take into account the width and height you previously set for the canvas element.

<canvas id="myChart" width="800" height="400"></canvas>

To fix this, you need to add configuration to your bar chart instance by passing an options object and setting maintainAspectRatio to false.

var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: months,
datasets: [{
label: 'Products sold monthly',
data: data,
options: {
maintainAspectRatio: false
}
}]
},
});

If you try again in the browser, you can see that the height of the bar chart is 400 pixels, but the width is ignored.

To do that responsive should be set to false for full-width control.

var myChart = new Chart(ctx, {
type: 'bar',
data: {
......
},
options: {
maintainAspectRatio: false,
responsive: false
}
})

Now if run your index.html on the browser again you will see that the width is 800px and the height is 400px.

Set Height and Width Using style.css:

Another way to control the width and height of the chart is with CSS. However, while this option requires additional markup in HTML, it is flexible because the width and height of the chart are controlled and responsive.

To do that remove the complete options object and replace the code inside your body tag with

<div class="chartWrapper">
<canvas id="myChart"></canvas>
</div>

And open your style.css and add the following code:

.chartWrapper {
max-width: 800px;
margin: auto;
}

Now if run your index.html on the browser again you will see it has a maximum width of 800px, and it is also responsive.

How We can Style Our Chart?

Now let’s add some styling on our chart.

➡️ backgroundColor – Takes an array of Hexadecimal or RGBA color values(strings) which will be used to color the bars in the chart.

➡️ borderColor – It takes an array of color values strings, the same as the backgroundColor property. It will color the borders of the bars.

➡️ borderWidth – It takes an Integer or a float value and it specifies how wide a border should be.

In order for you to understand how and when to use each property, we will add them one by one.

🔸 backgroundColor:

To color our bars, we will add the backgroundColor property with an array containing RGBA color values:

data: stars,
backgroundColor: [
"rgba(255, 99, 132, 0.2)"
]

You can add multiple colors as per your no. of values to give each of them a different color.

🔸 borderColor:

To create a bar chart border, pass an array of RGBA color values ​​using the borderColor property. Add it after the backgroundColor property. Same as the background color you can add more than one color for each bar.

Allows the borderColor property to work. We also need to add the borderWidth. Otherwise, the border will not be visible.

borderColor: [
"rgba(255, 99, 132, 1)",
],
borderWidth: 1

Try a Different Type of Chart

Now, what if you want to show the same data but with a Line chart is not very hard to do though.

The following are a few things we need to know:

  • backgroundColor is used to color the line points. We will just pass one color value, instead of passing on an array of values to style the points because we want the points to have the same color.
  • borderColor is used to color the line.
var myChart = new Chart(ctx, {
type: "line",
data: {
labels: months,
datasets: [
{
label: "Products sold monthly",
data: data,
backgroundColor: "rgba(255, 99, 132, 0.2)",
borderColor: "rgba(255, 99, 132, 1)",
borderWidth: 1
}
]
}
});
coma

Conclusion

In conclusion, Chart.js is a powerful and versatile JavaScript library that allows you to create visually appealing and interactive data visualizations. With its easy-to-use syntax and extensive documentation, Chart.js enables you to plot various types of charts, including bar, line, area, pie, bubble, radar, and scatter charts.

By integrating Chart.js into your web applications, blog posts, or presentations, you can effectively present data in a meaningful and engaging way. The library is open-source and freely available, making it accessible to users of all skill levels.

Keep Reading

Keep Reading

Mindbowser is excited to meet healthcare industry leaders and experts from across the globe. Join us from Feb 25th to 28th, 2024, at ViVE 2024 Los Angeles.

Learn More

Let's create something together!