Chart.js教程

1. chart.js 介绍

Chart.js是一个流行的由社区维护的开源数据可视化框架。它使我们能够生成响应式条形图、饼图、线图、甜甜圈图、散点图等。我们所要做的就是简单地指出你想在页面的什么地方显示图表,你想绘制什么样的图表,然后向 Chart.js 提供数据、标签和其他设置。在这之后,这个库就完成了所有繁重的工作。

1.1. Chart.js 特点

  • Chart.js 是开源的,由社区共同维护的开源项目。

  • Chart.js 支持 8 种图表类型,每种方式都具有动态效果并且可定制。

  • Chart.js 使用 HTML5 Canvas 技术,在所有现代浏览器(IE11+)上都有高效的绘图效率。

  • Chart.js 是响应式,可以根据窗口尺寸的变化重绘所有图表,展现更加细腻。

1.2. Chart.js 相关资料

2. chart.js 安装

我们可以从 npm、GitHub 版本或使用 Chart.js CDN 获取最新版本的 Chart.js。
如果使用的是前端框架(例如,React、Angular 或 Vue),可以查看可用的集成

实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!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" />
<title>Chart.js examples</title>
<script src="https://cdn.staticfile.org/Chart.js/4.0.1/chart.umd.min.js"></script>
<script>
window.onload = (event) => {
const container = document.getElementById('myChart');
    const myChart = new Chart(container, {...});
};
</script>
</head>
<body>
<div style="width: 600px; height: 600px">
<canvas width="400" height="400" id="myChart"></canvas>
</div>
</body>
</html>

使用 Chart.js

放置 canvas 画布

前面我们讲解了如何安装 chart.js 或将 chart.js 引入到我们的页面. 引入了 chart.js 后我们就可以开始使用 chart.js 了.

在使用 chart.js 库之前, 我们需要在页面放置一个<canvas>元素, 因为 Chart.js 需要使用 HTML5 画布来绘图。

首先我们需要在页面上引入 canvas 如下.

1
2
3
<div style="width:200px; height:400px;" >
<canvas width="400" height="400" id="myChart"></canvas>
</div>

从代码我们可以看出图表的大小比例是由 canvas 的宽度和高度来决定的, 而图表的实际宽高由父元素的宽高限定.

创建 Chart 对象

接下来我们需要创建 Canvas 对象. 在构造 Canvas 对象前, 我们需要了解它的 API 说明文档以及源代码.

通过查看Chart.js API 的官方文档Chart 类源代码, 我们发现构造 Chart 对象需要传递两个参数.

Chart 对象的构造器

1
2
3
4
5
6
7
8
9
10
constructor(item, userConfig) {
const config = this.config = new Config(userConfig);
const initialCanvas = getCanvas(item);
const existingChart = getChart(initialCanvas);
if (existingChart) {
throw new Error(
'Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' +
' must be destroyed before the canvas with ID \'' + existingChart.canvas.id + '\' can be reused.'
);
}

ChartItem

一个参数是 item 其类型为ChartItem, 它代表我们放置在界面的 Canvas 元素, 一个参数是 userConfig 用于指定图表的类型, 例如是饼图, 还是柱状图还是其它, 以及图形所需的数据, 以及图形的样式等.

通过查看 getCanvas 函数, 我们发现 item 参数可以是一个标识 Canvas 的 id 字符串, 也可以是一个 jquery 数组例如$('#myChart'), 也可以是一个 Canvas 元素例如document.getElementById('myChart') 或者 document.getElementById('myChart').getContext('2d');

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function getCanvas(item) {
if (_isDomSupported() && typeof item === 'string') {
item = document.getElementById(item);
} else if (item && item.length) {
// Support for array based queries (such as jQuery)
item = item[0];
}

if (item && item.canvas) {
// Support for any object associated to a canvas (including a context2d)
item = item.canvas;
}
return item;
}

userConfig

另外一个参数 userConfig, 其类型为ChartConfiguration <TType, TData, TLabel> | ChartConfigurationCustomTypesPerDataset <TType, TData, TLabel>, 由三部分组成: 类型, 数据, 和标签.

Chartjs 图表示例

以下实例我们创建一个简单的折线图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const canvas = document.getElementById("myChart");
const saleData = [
{month:"一月份", quantity: 65},
{month:"二月份", quantity: 59},
{month:"三月份", quantity: 80},
{month:"四月份", quantity: 81},
{month:"五月份", quantity: 56},
{month:"六月份", quantity: 55},
{month:"七月份", quantity: 40},
]; // 设置 X 轴上对应的标签
const data = {
labels: saleData.map(row => row.month),
datasets: [
{
label: "我的第一个折线图",
data: saleData.map(row => row.quantity),
fill: false,
borderColor: "rgb(75, 192, 192)", // 设置线的颜色
tension: 0.1,
},
],
};
const config = {
type: "line", // 设置图表类型
data: data,
};
const myChart = new Chart(canvas, config);

chartjs line chart

以下实例创建一个柱形图,显示不同颜色的票数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const canvas = document.getElementById("myChart");
const myChart = new Chart(canvas, {
type: "bar",
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "# 票数",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(255, 159, 64, 0.2)",
],
borderColor: [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)",
],
borderWidth: 1,
},
],
},
options: {
scales: {
y: {
beginAtZero: true,
},
},
},
});

Chartjs bar chart

接下来我们来看更多类型的 Chart 图表以及在使用这些图表的异同点.

Chart.js 柱状图

柱状图是一种以长方形的长度为变量的统计图表。

主要用于多个分类间的数据(大小、数值)的对比,可以用来显示一段时间内的数据变化或显示各项之间的比较情况,适用于二维数据集。柱状图的易用性和解释性使其成为最常用的图表之一.

柱形图的 type 属性为 bar ,type 描述了图表类型。

接下来我们创建一个简单的柱形图:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const canvas = document.getElementById("myChart");
const saleData = [
{month:"一月份", quantity: 65},
{month:"二月份", quantity: 59},
{month:"三月份", quantity: 80},
{month:"四月份", quantity: 81},
{month:"五月份", quantity: 56},
{month:"六月份", quantity: 55},
{month:"七月份", quantity: 40},
];
const data = {
labels: saleData.map(row => row.month),
datasets: [
{
label: "我的第一个柱形图",
data: saleData.map(row => row.quantity),
backgroundColor: [
// 设置每个柱形图的背景颜色
"rgba(255, 99, 132, 0.2)",
"rgba(255, 159, 64, 0.2)",
"rgba(255, 205, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(201, 203, 207, 0.2)",
],
borderColor: [
//设置每个柱形图边框线条颜色
"rgb(255, 99, 132)",
"rgb(255, 159, 64)",
"rgb(255, 205, 86)",
"rgb(75, 192, 192)",
"rgb(54, 162, 235)",
"rgb(153, 102, 255)",
"rgb(201, 203, 207)",
],
borderWidth: 1, // 设置线条宽度
},
],
};
const config = {
type: "bar", // 设置图表类型
data: data, // 设置数据集
options: {
scales: {
y: {
beginAtZero: true, // 设置 y 轴从 0 开始
},
},
},
};
const myChart = new Chart(canvas, config);

以上实例输出结果为:

Chartjs vertical bar chart

chart.js 还可以制作水平柱状图.

水平柱形图是垂直条形图的变,常用于显示数据趋势,以及并排比较多个数据集。

设置水平柱形图需要将选项对象中的 indexAxis 属性设置为 y,indexAxis 属性的默认值为 x。

1
2
3
4
5
6
7
8
const config = {
type: "bar", // 设置图表类型
data: data, // 设置数据集
options: {
indexAxis: "y",
},
};
const myChart = new Chart(canvas, config);

Chart.js 气泡图

气泡图用于展示三个变量之间的关系。

气泡的位置由前两个变量决定,对应的是 X 轴和 Y 轴,第三个参数为气泡的大小。

泡图的 type 属性为 bubble ,type 描述了图表类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const ctx = document.getElementById("myChart");
const data = {
datasets: [
{
label: "气泡图实例",
data: [
{
x: 20, // X 轴
y: 30, // Y 轴
r: 15, // 气泡半径
},
{
x: 30,
y: 20,
r: 20,
},
{
x: 40,
y: 10,
r: 10,
},
],
backgroundColor: "rgb(255, 99, 132)",
},
],
};
const config = {
type: "bubble", // 设置图表类型
data: data, // 设置数据集
options: {},
};
const myChart = new Chart(ctx, config);

以上实例输出结果为:

Chart.js bubble chart

Chart.js 环形图

环形图又叫做甜甜圈图,其本质是饼图将中间区域挖空。

环形图是由两个及两个以上大小不一的饼图叠在一起,挖去中间的部分所构成的图形。

  • 饼图是用圆形及圆内扇形的角度来表示数值大小的图形,它主要用于表示一个样本(或总体)中各组成部分的数据占全部数据的比例,对于研究结构性问题十分有用。

  • 环形图与饼图类似,但又有区别。环形图中间有一个”空洞”,每个样本用一个环来表示,样本中的每一部分数据用环中的一段表示。因此环形图可显示多个样本各部分所占的相应比例,从而有利于构成的比较研究。

环形图 type 属性为 doughnut ,type 描述了图表类型。

接下来我们创建一个简单的环形图:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const myCanvas = document.getElementById("myChart");
const data = [
{color: "Red", count: 300},
{color: "Blue", count: 50},
{color: "Red", count: 100}
]
const config = {
type: "doughnut",
data: {
labels: data.map(row => row.color),
datasets: [
{
label: "环形图实例",
data: data.map(row => row.count),
backgroundColor: [
"rgb(255, 99, 132)",
"rgb(54, 162, 235)",
"rgb(255, 205, 86)",
],
hoverOffset: 4,
},
],
},
options: {
responsive: true, // 设置图表为响应式,根据屏幕窗口变化而变化
maintainAspectRatio: false, // 保持图表原有比例
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
},
};
const myChart = new Chart(myCanvas, config);

以上实例输出结果为:

Chartjs doughnut chart

Chart.js 饼图

饼图,或称饼状图,是一个划分为几个扇形的圆形统计图表,用于描述量、频率或百分比之间的相对关系。在饼图中,每个扇区的弧长(以及圆心角和面积)大小为其所表示的数量的比例。这些扇区合在一起刚好是一个完全的圆形。顾名思义,这些扇区拼成了一个切开的饼形图案。

饼图 type 属性为 pie ,type 描述了图表类型。

接下来我们创建一个简单的饼图:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const myCanvas = document.getElementById("myChart");
const data = [
{ color: "Red", count: 300 },
{ color: "Blue", count: 50 },
{ color: "Red", count: 100 },
];
const config = {
type: "pie",
data: {
labels: data.map(row=> row.color),
datasets: [
{
label: "饼图实例",
data: data.map(row=> row.count),
backgroundColor: [
"rgb(255, 99, 132)",
"rgb(54, 162, 235)",
"rgb(255, 205, 86)",
],
hoverOffset: 4,
},
],
},
options: {
responsive: true, // 设置图表为响应式,根据屏幕窗口变化而变化
maintainAspectRatio: false, // 保持图表原有比例
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
},
};
const myChart = new Chart(myCanvas, config);

以上实例输出结果为:

Chartjs pie chart

Chart.js 折线图

折线图是排列在工作表的列或行中的数据可以绘制到折线图中。

折线图可以显示随时间(根据常用比例设置)而变化的连续数据,因此非常适用于显示在相等时间间隔下数据的趋势。

折线图 type 属性为 line ,type 描述了图表类型。

接下来我们创建一个简单的折线图:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const myCanvas = document.getElementById("myChart");
const data = [
{ month: "一月份", quantity: 65 },
{ month: "二月份", quantity: 59 },
{ month: "三月份", quantity: 80 },
{ month: "四月份", quantity: 81 },
{ month: "五月份", quantity: 56 },
{ month: "六月份", quantity: 55 },
{ month: "七月份", quantity: 40 },
];
const config = {
type: "line", // 设置图表类型
data: {
labels: data.map(row=>row.month),
datasets: [
{
label: "我的第一个折线图",
data: data.map(row=>row.quantity),
fill: false,
borderColor: "rgb(75, 192, 192)", // 设置线的颜色
tension: 0.1,
},
],
},
};
const myChart = new Chart(myCanvas, config);

Chartjs line chart

Chart.js 混合图

Chart.js 可以创建由两种或多种不同图表类型组合而成的混合图表,比如条形图与折线图的混合。

创建混合图表时,我们在每个数据集上指定图表类型。

混合图 type 属性为 scatter。

柱形图 type 属性为 bar ,折线图 type 属性为 line , type 描述了图表类型。

接下来我们创建一个简单的混合图:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const myCanvas = document.getElementById("myChart");
const saleData = [
{ month: "一月份", quantity: 45, amount: 50.0 },
{ month: "二月份", quantity: 49, amount: 40.0 },
{ month: "三月份", quantity: 52, amount: 45.0 },
{ month: "四月份", quantity: 48, amount: 49.0 },
];
const data = {
labels: saleData.map((row) => row.month),
datasets: [
{
type: "bar",
label: "柱形图数据集",
data: saleData.map((row) => row.quantity),
borderColor: "rgb(255, 99, 132)",
backgroundColor: "rgba(255, 99, 132, 0.2)",
},
{
type: "line",
label: "折线图数据集",
data: saleData.map((row) => row.amount),
fill: false,
borderColor: "rgb(54, 162, 235)",
},
],
};
const config = {
type: "scatter",
data: data,
options: {
responsive: true, // 设置图表为响应式,根据屏幕窗口变化而变化
maintainAspectRatio: false, // 保持图表原有比例
scales: {
y: {
beginAtZero: true,
},
},
},
};
const myChart = new Chart(myCanvas, config);

以上实例输出结果为:

Chartjs combinated chart

Chart.js 极地图

极区图类似于饼图,但每个数据集具有相同的角度,线段的半径根据提供的值有所不同。

混合图 type 属性为 polarArea。

接下来我们创建一个简单的极地图:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const ctx = document.getElementById("myChart");
const data = {
labels: ["Red", "Green", "Yellow", "Grey", "Blue"],
datasets: [
{
label: "极地图实例",
data: [11, 16, 7, 3, 14],
backgroundColor: [
"rgb(255, 99, 132)",
"rgb(75, 192, 192)",
"rgb(255, 205, 86)",
"rgb(201, 203, 207)",
"rgb(54, 162, 235)",
],
},
],
};
const config = {
type: "polarArea",
data: data,
options: {
responsive: true, // 设置图表为响应式,根据屏幕窗口变化而变化
maintainAspectRatio: false, // 保持图表原有比例
},
};
const myChart = new Chart(ctx, config);

以上实例输出结果为:

polarArea chart

Chart.js 雷达图

雷达图是一种显示多个数据点及其之间变化的方式。

雷达图是以从同一点开始的轴上表示的三个或更多个定量变量的二维图表的形式显示多变量数据的图形方法。

轴的相对位置和角度通常是无信息的。

混合图 type 属性为 radar。

接下来我们创建一个简单的雷达图:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const ctx = document.getElementById("myChart");
const data = {
labels: [
"Eating",
"Drinking",
"Sleeping",
"Designing",
"Coding",
"Cycling",
"Running",
],
datasets: [
{
label: "第一个数据集",
data: [65, 59, 90, 81, 56, 55, 40],
fill: true,
backgroundColor: "rgba(255, 99, 132, 0.2)",
borderColor: "rgb(255, 99, 132)",
pointBackgroundColor: "rgb(255, 99, 132)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgb(255, 99, 132)",
},
{
label: "第二个数据集",
data: [28, 48, 40, 19, 96, 27, 100],
fill: true,
backgroundColor: "rgba(54, 162, 235, 0.2)",
borderColor: "rgb(54, 162, 235)",
pointBackgroundColor: "rgb(54, 162, 235)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgb(54, 162, 235)",
},
],
};
const config = {
type: "radar",
data: data,
options: {
responsive: true, // 设置图表为响应式,根据屏幕窗口变化而变化
maintainAspectRatio: false, // 保持图表原有比例
elements: {
line: {
borderWidth: 3, // 设置线条宽度
},
},
},
};
const myChart = new Chart(ctx, config);

以上实例输出结果为:

Chartjs radar chart

Chart.js 散点图

散点图是由两组数据构成多个坐标点,考察坐标点的分布,判断两变量之间是否存在某种关联或总结坐标点的分布模式。

散点图 type 属性为 scatter。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const ctx = document.getElementById("myChart");
const data = {
datasets: [
{
label: "散点图实例",
data: [
{
x: -10,
y: 0,
},
{
x: 0,
y: 10,
},
{
x: 10,
y: 5,
},
{
x: 0.5,
y: 5.5,
},
],
backgroundColor: "rgb(255, 99, 132)",
},
],
};
const config = {
type: "scatter",
data: data,
options: {
responsive: true, // 设置图表为响应式,根据屏幕窗口变化而变化
maintainAspectRatio: false, // 保持图表原有比例
scales: {
x: {
type: "linear",
position: "bottom",
},
},
},
};
const myChart = new Chart(ctx, config);

以上实例输出结果为:

Chartjs scatter chart

3. 参考文档

快学网-刘力超–chart.js 图表创建

Chart.js 中文教程

Chart.js 教程