DEV Community

Cover image for Data visualization with Chart.js
Ivana
Ivana

Posted on

Data visualization with Chart.js

Chart.js is extremely popular and powerful JavaScript library which is used for visualizing data and to generate beautiful charts for a webpage.

It uses the HTML5 Canvas element for rendering and supports all modern browsers (IE11+) and provides beautiful flat designs for charts.

Chart.js supports 8 chart types: bar, line, area, pie (doughnut), bubble, radar, polar, and scatter.

Installation

Chart.js can be installed via npm or bower.

npm

npm install chart.js --save

Bower

bower install chart.js --save

Usage

Chart.js can be used with ES6 modules, plain JavaScript and module loaders.

Creating a Chart

To create a chart, we need to instantiate the Chart class. To do this, we need to pass in the node, jQuery instance, or 2d context of the canvas of where we want to draw the chart. Here's an example.

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

var ctx = document.getElementById('myChart');
var ctx = document.getElementById('myChart').getContext('2d');
var ctx = $('#myChart');
var ctx = 'myChart';
// Any of the following formats may be used

Chart.js comes with built-in chart types:

line
bar
radar
doughnut and pie
polar area
bubble
scatter

Alt Text

Line Example Usage

var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});

Alt Text

Bar Example Usage

var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});

Alt Text

Radar Example Usage

var myRadarChart = new Chart(ctx, {
type: 'radar',
data: data,
options: options
});

Alt Text

Doughnut and Pie Example Usage

// For a pie chart
var myPieChart = new Chart(ctx, {
type: 'pie',
data: data,
options: options
});

// And for a doughnut chart
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: options
});

Alt Text

Polar area Example Usage


new Chart(ctx, {
data: data,
type: 'polarArea',
options: options
});

Alt Text

Bubble Chart Example Usage

// For a bubble chart
var myBubbleChart = new Chart(ctx, {
type: 'bubble',
data: data,
options: options
});

Alt Text

Scatter Chart

Scatter charts are based on basic line charts with the x axis changed to a linear axis. To use a scatter chart, data must be passed as objects containing X and Y properties. The example below creates a scatter chart with 3 points.

var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'Scatter Dataset',
data: [{
x: -10,
y: 0
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}]
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
}
}
});

To connect with me please check my Github, LinkedIn or Twitter.

Thank you for reading!

Top comments (0)