Home > Web Front-end > CSS Tutorial > Fancy, Responsive Charts with Chart.js

Fancy, Responsive Charts with Chart.js

William Shakespeare
Release: 2025-02-26 00:05:15
Original
952 people have browsed it

Fancy, Responsive Charts with Chart.js

Data is all around us. While search engines and other applications work most optimally with text based representation of data, people find data represented visually to be easy to comprehend. Earlier this year, SitePoint published Aurelio’s article presenting an introduction to Chart.js. This tutorial will provide a quick recap of that introduction followed by a deeper look into the features of Chart.js.

Key Takeaways

  • Chart.js is an HTML5 canvas-based responsive, light-weight charting library that supports six different chart types, each with numerous customization options. It is modular, allowing developers to only include the chart types they need, keeping the file size minimal.
  • The library allows for extensive customization of charts, including tool tips, animation, and even the creation of custom chart types. This includes both global settings and chart-specific options, with the ability to make charts responsive by setting the responsive configuration option to true.
  • Chart.js also supports dynamic addition and removal of data, making it ideal for situations where data changes over time, such as stock market representations. This can be achieved through methods like removeData() and addData(valuesArray,label), or by directly setting the values in a chart.

Getting Started

Chart.js is an HTML5 canvas based responsive, flexible, light-weight charting library. The library supports six different chart types, each of these chart types coming with a load of customization options. If that is not enough, you also have the ability to create your own custom chart types.

All six core chart types in Chart.js are just 11kb minified and gzip’d and the library is modular so you can further reduce the request size for the file by only including the chart type that you actually need. Below is the cdnjs link to include it:

<span><script></script></span>
Copy after login

Available Configuration Options

Chart.js allows you to change almost every aspect of your charts — from tool tips to animation. In this section I will modify a few settings to demonstrate what Chart.js is capable of creating. Here is the HTML we’ll start with:

<span><canvas id="canvas"></canvas></span>
Copy after login
Copy after login

For the first demonstration, I will create a line chart. There are some basic options that you need to set for the charts to make sense. The line chart expects an array of labels and datasets. The labels appear on the X axis. I have filled up the line chart with some dummy data. The data is broken up into an array of data sets. Each data set has a color for the fill, the line, and the points.

I have set fillColor to transparent in this case. If you don’t set a value of fillColor it will be set to black or grey instead. Same goes for other values. The colors are defined using RGBA, RGB, hex, or HSL format, similar to CSS.

<span><script src="https://img.php.cn/upload/article/000/000/000/174049952240765.jpg"></script></span>
Copy after login

Setting Global Options

I have included the code that sets some global values. animationSteps determines animation duration. There are many more options that you can modify according to your needs, such as scaleLineColor and scaleIntegersOnly. I suggest that you go through the Chart.js documentation to see what else this library has to offer.

<span><canvas id="canvas"></canvas></span>
Copy after login
Copy after login

Setting Chart Specific Options

Besides Global options, there are configuration options available for individual chart types. I will set a few of these options in this line chart to give you an idea:

<span>var lineData = {
</span>  <span>labels: ['Data 1', 'Data 2', 'Data 3', 'Data 4', 
</span>           <span>'Data 5', 'Data 6', 'Data 7'],
</span>  <span>datasets: [{
</span>    <span>fillColor: 'rgba(0,0,0,0)',
</span>    <span>strokeColor: 'rgba(220,180,0,1)',
</span>    <span>pointColor: 'rgba(220,180,0,1)',
</span>    <span>data: [20, 30, 80, 20, 40, 10, 60]
</span>  <span>}, {
</span>    <span>fillColor: 'rgba(0,0,0,0)',
</span>    <span>strokeColor: 'rgba(151,187,205,1)',
</span>    <span>pointColor: 'rgba(151,187,205,1)',
</span>    <span>data: [60, 10, 40, 30, 80, 30, 20]
</span>  <span>}]
</span><span>}</span>
Copy after login

Charts generated by Chart.js are not responsive by default. Setting responsive to true (as done above) makes them responsive. If you need to make every chart responsive, I recommend that you set this globally instead, like this:

<span>Chart.defaults.global = {
</span>  <span>animationSteps : 50,
</span>  <span>tooltipYPadding : 16,
</span>  <span>tooltipCornerRadius : 0,
</span>  <span>tooltipTitleFontStyle : 'normal',
</span>  <span>tooltipFillColor : 'rgba(0,160,0,0.8)',
</span>  <span>animationEasing : 'easeOutBounce',
</span>  <span>scaleLineColor : 'black',
</span>  <span>scaleFontSize : 16
</span><span>}</span>
Copy after login

Below you can see the demo of the line chart:

See the Pen Chart.js Line Chart Demo by SitePoint (@SitePoint) on CodePen.

Adding and Removing Data Dynamically

Sometimes you need to display data that changes over time. A classic example of this scenario is the stock market. In this section I will create a bar chart and dynamically remove as well as add data to it. I will be using some random data and I have decided to represent data with a bar chart in this case. Most of the code in this example will be similar to the previous example. Once we have our HTML (same as previous example), we can add our JavaScript.

First we will write code to fill up our chart with dummy data. I use a function expression to generate random values and then store it in a variable dData . These values are then used to provide us with random data whenever the need arises. As in the previous example, I create an array of labels and datasets and set an arbitrary fillColor.

<span>var ctx = document.getElementById('canvas').getContext('2d');
</span><span>var lineDemo = new Chart(ctx).<span>Line</span>(lineData, {
</span>  <span>responsive: true,
</span>  <span>pointDotRadius: 10,
</span>  <span>bezierCurve: false,
</span>  <span>scaleShowVerticalLines: false,
</span>  <span>scaleGridLineColor: 'black'
</span><span>});</span>
Copy after login

Now it’s time to write the code that removes and adds bars to our chart. I begin by initializing the index variable at a value of 11. I am using two methods: removeData() and addData(valuesArray,label). Calling removeData() on a chart instance removes the first value for all datasets on that particular chart. In case of barChartDemo, the first value of the dataset is removed. Calling addData() passing an array of values along with labels adds a new data point at the end of the chart. The code snippet below updates the chart every 3 seconds.

<span>Chart.defaults.global.responsive = true;</span>
Copy after login

An alternative method to update values in a chart is to set the values directly. In the example below, the first line sets the value of the second bar of the first dataset to 60. If you call update at this point, the bar will animate from its current value to 60.

<span>var dData = function() {
</span>  <span>return Math.round(Math.random() * 90) + 10;
</span><span>};
</span>
<span>var barData = {
</span>  <span>labels: ['dD 1', 'dD 2', 'dD 3', 'dD 4',
</span>           <span>'dD 5', 'dD 6', 'dD 7', 'dD 8'],
</span>  <span>datasets: [{
</span>    <span>fillColor: 'rgba(0,60,100,1)',
</span>    <span>strokeColor: 'black',
</span>    <span>data: [dData(), dData(), dData(), dData(),
</span>           <span>dData(), dData(), dData(), dData()]
</span>  <span>}]
</span><span>}</span>
Copy after login

And here is the bar chart demo:

See the Pen Chart.js Responsive Bar Chart Demo by SitePoint (@SitePoint) on CodePen.

Conclusion

This tutorial covered some important features of Chart.js. The first example demonstrated the use of a few global settings. However, Chart.js also provides customization options specific for a chart type. The library allows you to create your own chart types if charts already available don’t meet your requirements. I recommend you to go through the documentation so you can gain a good grasp of what you can and cannot do with this library.

Frequently Asked Questions (FAQs) about Fancy Responsive Charts with Chart.js

How can I make my Chart.js chart fully responsive?

Making your Chart.js chart fully responsive involves setting the responsive configuration option to true. This allows the chart to resize itself when the window size changes. You can do this by adding the following code to your chart configuration:

var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
responsive: true
}
});
This code will ensure that your chart adjusts its size whenever the window size changes, ensuring a fully responsive design.

Why is my Chart.js chart not resizing correctly?

If your Chart.js chart is not resizing correctly, it could be due to a few reasons. One common issue is that the canvas element containing the chart is not being resized correctly. Ensure that the canvas element has a relative position and a width and height of 100%. Another issue could be that the responsive option in the chart configuration is not set to true. Check your chart configuration to ensure that the responsive option is set correctly.

How can I customize the appearance of my Chart.js chart?

Chart.js provides a wide range of options for customizing the appearance of your charts. You can customize the colors, labels, tooltips, and much more. For example, to customize the color of the bars in a bar chart, you can use the following code:

var myChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
backgroundColor: 'rgba(75, 192, 192, 0.2)'
}]
}
});
This code will set the background color of the bars to a light blue color. You can customize many other aspects of the chart’s appearance using similar options.

How can I add tooltips to my Chart.js chart?

Tooltips in Chart.js are enabled by default and will appear when you hover over data points on the chart. You can customize the appearance and behavior of tooltips using the tooltips configuration option. For example, to change the background color of tooltips, you can use the following code:

var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
tooltips: {
backgroundColor: 'rgba(0, 0, 0, 0.8)'
}
}
});
This code will set the background color of tooltips to a semi-transparent black color. You can customize many other aspects of tooltips using similar options.

How can I add animations to my Chart.js chart?

Chart.js provides a variety of options for adding animations to your charts. You can control the duration, easing function, and other aspects of animations using the animation configuration option. For example, to animate the chart with a duration of 2000 milliseconds and an easing function of ‘easeOutBounce’, you can use the following code:

var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
animation: {
duration: 2000,
easing: 'easeOutBounce'
}
}
});
This code will animate the chart with a bouncing effect over a duration of 2 seconds. You can customize many other aspects of animations using similar options.

The above is the detailed content of Fancy, Responsive Charts with Chart.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template