Create Awesome Charts using Chart.js

Page content

Chart.js is an excellent tool for creating wonderful and awesome looking interactive charts. It is simple to use and you do not need to know much javascript to create charts in chart.js. You simply must be able to understand some code and be able to edit code to customize charts according to your need.

Chart.js makes it easier to create charts and manipulate data for making awesome charts and displaying them on your website. Whether you are using Wordpress or any other CMS, you can use chart.js to display charts on your website. Another important factor to know about chart.js is that it is highly customizable and loads fast or will have no significant impact on loading speed even if you are using a CMS like Wordpress. So, for Wordpress users, it is a lot better to use chart.js instead of some heavy plugin for displaying charts.

Chart.js is free which means you do not need to spend for any feature and still there are tons of customizations that you would not find easily in any software or plugin. Installing chart.js is also easy and the best installation method is to use the cdn link in the website head. Otherwise, you can also install it on your server using npm.

Chart.js is currently the best free tool for creating a large variety of charts including bar charts, line charts, pie charts, doughnut charts, bubble charts, mixed charts, radar charts and scatter charts. You can make awesome, colorful and interactive charts using chart.js. There are several customizations including animations to make your charts visually stunning and compelling charts.

Installing chart.js

Let’s begin with the installation of the chart which comes as a third party library. The easiest method to install the chart is to insert the cdn link into the head. The latest version of chart.js right now is 4.4.0. You can add the code below to your website head to start using the chart.

Cloudflare CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.js" integrity="sha512-6LKCH7i2+zMNczKuCT9ciXgFCKFp3MevWTZUXDlk7azIYZ2wF5LRsrwZqO7Flt00enUI+HwzzT5uhOvy6MNPiA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

js Delivr

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>

Otherwise, if you want you can install it using npm with the following command:

npm install chart.js

Once chart.js has been installed, you are ready to go and can start creating charts based on your needs.

Creating Bar graphs with chart.js

First, we will create a basic bar graph with only one dataset. Let me show you what the code for creating charts in chart.js looks like. The code for creating a basic bar graph with six bars is as follows:

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

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
  const ctx = document.getElementById('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],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });
</script>

Now, let me explain the above piece of code. You first need to create the canvas to draw the chart. The first few lines of code do exactly that.

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

Next, we included chart.js from a cdn using the following script.

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

Rest of the script is used to render the actual chart. We start by setting the chart type to bar and then include the labels and the dataset. The labels are shown along the x axis. The datasets include a label which is basically nothing but the focal point of the chart. For example, if you are plotting the number of votes in the chart, # of votes is the label which can be shown at the top or bottom of the chart and can be included in the tooltip. All you need to do now is to insert the above script into the html body of your webpage and it will load the chart you have created.

The above script does not include data labels or the tooltip. However, we will discuss these things also as well as more configurations for creating an interactive, user friendly and more attractive chart. You can configure the various options for your chart with ‘options’. As you can see in the above script, we have set y axis to ‘beginAtZero: true’. If you set it to false, the chart will not show all the bars from zero to the top value (means bars will not start from zero but at a more appropriate base value like 10 or 20) or you will have shorter bars. So, you can set it to false if you want to have shorter bars. You can also set the minimum and maximum values for the bars in the chart using suggestedMin and suggestedMax options which we will discuss later.

There are more similar configurations that will help you alter the look and behavior of your chart including animations, and other configurations like tooltip or the chart data labels. For example, you may like to have labeled charts which show the value on the canvas. If you apply tooltip, the user can check out the value by hovering on the bar area. However, if you want to draw a line chart instead of a bar chart from your data, you will not need to change much. All you need to do is to change the chart type from bar to line in the above script.

Create chart with chart.js

The above chart will look even more attractive when we apply different background colors and apply data labels to our chart. Applying data labels makes the charts simply more readable.

Dealing with more than one datasets in chart.js

In the previous chart, we were dealing with only one dataset. Sometimes, you may need to compare two types of more in the same chart. For example, you may want to compare the sales of a brand in three different regions over the past four-five years. Since, we are comparing sales in three different regions, we will have three different datasets. It is very easy to deal with more than one datasets in chart.js. You can include more than one datasets in the data section of the script.

As you can see in the above script, the dataset contains the label followed by the data. What if we wanted to include the number of votes over two different years and plot them in a chart. To achieve that, we will need to include two different datasets together, which is possible in the following manner:

  data: {
      labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
   datasets: [
       {label: '# of Votes in 2022',
        data: [12, 19, 3, 5, 2, 3]},
       {label: '# of Votes in 2023',
        data: [22, 29, 13, 15, 12, 13]},
         ]},

charts with chart.js

Above, you can see we have included the data for two years in two different datasets. You can include more datasets according to your need. You will see two differently colored bars representing the data for each year in the chart like shown in the image below. However, you can assign a color of your choice to each dataset using the backgroundColor property in the following manner.

  data: {
      labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
   datasets: [
       {label: '# of Votes in 2022',
        backgroundColor:"#58508d",
        data: [12, 19, 3, 5, 2, 3]},
       {label: '# of Votes in 2023',
       backgroundColor:"#003f5c",
        data: [12, 19, 3, 5, 2, 3]},
         ]},

Now, the bar chart will have bars in two different colors and one color representing each year which makes it more visually appealing as well as simpler. If you are plotting multiple datasets on the same chart, you can add a backgroundColor of your choice to each one. It will also make the chart clearer and easier to read as well as attractive.

So, this is how you can create basic charts in chart.js. However, there is much more to do with charts in chart.js like labeling the bars and editing the tooltip. If you need a simple chart, the default tooltip will do the job. Still, you might like to know that you can also edit the default tooltip and its behavior.

Note: To make your chart responsive, just set responsive to true in options. Check the code below:

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

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
  const ctx = document.getElementById('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],
        borderWidth: 1
      }]
    },
    options: { responsive: true, //responsive is set to true
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });
</script>

Adding data labels to charts in chart.js

So, this is how you can create simple interactive bar charts in chart.js in attractive colors. However, there is still one more thing that you would like to do with your bar chart, which is to show the data labels. Users will not always need to hover over the chart to read the data.

charts with chart.js

In chart.js, datalabels are available in the form of a plugin that can be called via cdn and needs to be registered. You can add it with the following script in the same way as you installed chart.js using a cdn link:

<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>

Otherwise, you can install it with npm:

npm install chartjs-plugin-datalabels --save

Once you have installed the plugin, you can integrate it into the chart and register it to use it.

Now, we will try to add data labels to our original graph by editing the code. All we need to do is to integrate the plugin and register it for use in the chart. Check the code below:

<div>
  <canvas id="myChart1"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.2.0/dist/chartjs-plugin-datalabels.min.js"></script> //integrate dataLabels plugin

<script>
  var ctx = document.getElementById('myChart1');
 Chart.register(ChartDataLabels); //registered DataLabels plugin
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
      datasets: [{
        label: '# of Votes in 2022',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },{label: '# of Votes in 2023',
        data: [22, 29, 13, 15, 12, 13]},
]
    },
    options: { 
plugins:
{datalabels: {align: 'top', anchor: 'end', color:'black', font: { size: 10}}, //changes to the datalabels configuration.
},
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });
</script>

That’s all and now you have the data labels showing at the top of the bars. The default position of the datalabels is center. To change the default position, we have made more changes to dataLabels configuration. As you can see in the above piece of code, we have added changes to ‘options’. The properties that affect datalabel position are align and anchor and the color property affects the text color. We have also specified the font size for our data labels.

Our final chart looks like the following.

chart and datalabels in chart.js

Making charts with chart.js is fun and there is more to do with chart.js. In the next section of this tutorial, we will discuss more configuration changes and chart types.

Even if you are using a CMS like Wordpress, you can use chart.js to display attractive charts on your blog/website. To insert a chart in Wordpress, you can add the script to the post/page using html block. Yoou can also take a preview of the chart in Wordpress when you are using the html block to insert the script into a page. Just searh for the html block and add it and then paste the script inside the block. Now, publish the changes and check out the magic at the front end.