chart.min.js
This article is included in our anthology, Modern JavaScript. If you want everything in one place to get up to speed on modern JavaScript, sign up for SitePoint Premium and download yourself a copy.
本文包含在我们的选集Modern JavaScript中 。 如果您希望所有内容都集中在一个地方,以适应最新JavaScript,请注册SitePoint Premium并下载一个副本。
This article was peer reviewed by Tim Severien and Simon Codrington. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!
本文由Tim Severien和Simon Codrington进行同行评审。 感谢所有SitePoint的同行评审人员使SitePoint内容达到最佳状态!
If your website is data-intensive, then you will need to find a way to make that data easy to visualize. Humans, after all, are not wonderful at understanding long lists of raw numbers. That’s where charts and graphs come in — they can make complicated statistical relationships obvious and intuitive, as well as more accessibile to non-English speakers. Everyone understands basic charts at the same speed, the same can’t be said for paragraphs rife with technical jargon. Using charts when it’s beneficial, will make your website easier to understand and visually more appealing.
如果您的网站是数据密集型网站,那么您将需要找到一种使数据易于可视化的方法。 毕竟,人类在理解一长串原始数字方面并不出色。 这就是图表出现的地方-它们可以使复杂的统计关系变得明显和直观,并使非英语国家的用户更容易使用。 每个人都以相同的速度理解基本图表,对于用技术术语充斥的段落则不能这么说。 在有益的情况下使用图表将使您的网站更易于理解,并且在视觉上更具吸引力。
In this article I’ll introduce you to a JavaScript charting library called Chart.js. Using six stylish examples, I’ll demonstrate how you can use Chart.js to visualize data on your website, as well as configure it to meet your needs.
在本文中,我将向您介绍一个名为Chart.jsJavaScript图表库。 通过六个时尚的示例,我将演示如何使用Chart.js可视化网站上的数据,以及如何配置它以满足您的需求。
I chose Chart.js because it can be learned and leveraged quickly. It’s designed with simplicity in mind, yet is extremely customizable. In my experience, charting libraries fall onto a spectrum of complexity, where more complex libraries offer deeper customization, but have steeper learning curves. Chart.js is one of the quickest and easiest libraries to learn that doesn’t heavily limit your options. It comes with eight different chart types that will cover almost all of your data visualization needs.
我选择Chart.js是因为可以快速学习和利用它。 它在设计时考虑了简单性,但可高度自定义。 以我的经验,图表库属于复杂性范围,其中更复杂的库提供了更深入的自定义功能,但学习曲线更陡峭。 Chart.js是学习最快,最简单的库之一,它不会严重限制您的选择。 它带有八种不同的图表类型,几乎可以满足您所有数据可视化需求。
Chart.js is actively maintained to a high standard by the open source community. It recently reached version 2.0, which came with a few fundamental syntax changes to make code more consistent, as well as offer mobile support. In this article, I’m going to use Chart.js 2.0 and it’s updated syntax. At the end of this article, after giving you a chance to see how Chart.js 2.0 works, there is a section covering the 1.0 -> 2.0 transition and what to expect when reading old Chart.js examples online.
开源社区积极地将Chart.js维持在高标准下。 它最近达到了2.0版,其中进行了一些基本语法更改,以使代码更加一致,并提供了移动支持。 在本文中,我将使用Chart.js 2.0及其更新的语法。 在本文的结尾,在使您有机会了解Chart.js 2.0的工作原理之后,有一节介绍了1.0-> 2.0过渡以及在线阅读旧Chart.js示例时的期望。
Again, Chart.js is focused on being easy. Easy to learn, easy to leverage, and easy to install. If you’d like to dive into the actual code, check out the GitHub project.
同样,Chart.js专注于轻松。 易于学习,易于利用和易于安装。 如果您想深入了解实际代码, 请查看GitHub project 。
You only need two things to use Chart.js.
使用Chart.js只需要两件事。
1) The library – for this guide, I recommend using a CDN because it’s the easiest way to get up and running fast.
1)库–对于本指南,我建议使用CDN,因为它是快速启动和运行的最简单方法。
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>
2) A <canvas>
element, as Chart.js leverages HTML5 canvas.
2) <canvas>
元素,因为Chart.js利用HTML5画布。
</canvas><canvas id="myChart"></canvas>
Alternatively, you can use a package manager to download the library. For more information, see the Getting Started guide.
或者,您可以使用程序包管理器来下载库。 有关更多信息,请参见《 入门指南》。
Simple, eh? Now without further ado, let’s look at what Chart.js has to offer.
简单吧? 现在,不用多说了,让我们看看Chart.js提供了什么。
This is all you need to create a minimum line chart in Chart.js. Just put it inside of a <script></script>
somewhere in your <body>
after you declare the HTML5 canvas.
这就是在Chart.js中创建最小折线图所需的全部。 声明HTML5画布后,只需将其放在<body>
某个地方的<script></script>
中即可。
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
datasets: [{
label: 'apples',
data: [12, 19, 3, 17, 6, 3, 7],
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'oranges',
data: [2, 29, 5, 5, 2, 3, 10],
backgroundColor: "rgba(255,153,0,0.4)"
}]
}
});
See the Pen 2 – Line chart by SitePoint (@SitePoint) on CodePen.
请参阅CodePen上的SitePoint ( @SitePoint )的Pen 2 –折线图 。
If this code looks intense, don’t worry! All Chart.js examples follow the above format for the most part, so you only have to learn it once. Lets go line by line to understand what’s happening.
如果这段代码看起来很紧张,请不要担心! 所有Chart.js示例在大多数情况下都遵循上述格式,因此您只需学习一次即可。 让我们一行一行地了解正在发生的事情。
var ctx = document.getElementById("myChart").getContext('2d');
This line gets a reference to the <canvas>
element we created earlier, then calls the getContext
method on it. The getContext
method returns an object that provides methods and properties for drawing on the canvas. We store this in a variable named ctx
.
此行获取对我们之前创建的<canvas>
元素的引用,然后在其上调用getContext
方法。 getContext
方法返回一个对象,该对象提供用于在画布上绘制的方法和属性 。 我们将此存储在名为ctx
的变量中。
var myChart = new Chart(ctx, {
type: 'line',
data: // array of line data goes here
});
Here we are creating the chart object. I’ve excluded the data for a moment to focus on the type
property, which determines the type of chart we want. Chart.js’ new Chart()
constructor takes two parameters:
在这里,我们正在创建图表对象。 我暂时排除了数据,只关注type
属性,它确定了我们想要的图表的类型。 Chart.js的new Chart()
构造函数采用两个参数:
Either a reference to a </canvas><canvas>
element that the chart will be rendered on, or a reference to its 2d drawing context (here we are using the 2d context). Regardless of which you use, the Chart.js convention is to call it ctx
.
引用将要渲染图表的</canvas><canvas>
元素,或者引用其2d绘图上下文(此处使用2d上下文)。 无论使用哪种方式,Chart.js约定都将其称为ctx
。
An object literal containing the data and the configuration options that Chart.js will use to build your chart. The required properties are type
and data
. In our example type
is ‘line’ because we want a line chart. data
is the data you used to populate the chart.
一个对象文字,其中包含Chart.js将用来构建图表的数据和配置选项。 必需的属性是type
和data
。 在我们的示例中, type
为“折线”,因为我们需要折线图。 data
是用于填充图表的数据。
Chart.js uses array location to determine graph position, so the first point of ‘apples’ will have the value ’12’, the second will have ’19’, and so on. Adding new lines is as easy as adding a new object with a label
and data
.
Chart.js使用数组位置来确定图形位置,因此“苹果”的第一个点的值为“ 12”,第二个点的值为“ 19”,依此类推。 添加新行就像添加带有label
和data
的新对象一样容易。
Finally, I have set an rgba background color for each data set to make it more visually appealing.
最后,我为每个数据集设置了rgba背景色,以使其在视觉上更具吸引力。
To learn more about line charts with Chart.js, check out the docs
要了解有关Chart.js的折线图的更多信息, 请查看文档
Pro tip: clicking on any of the legends for the charts (“Apples” and “Oranges” here) will toggle that particular data set. This works for all chart types.
专业提示:单击图表的任何图例(此处为“ Apples”和“ Oranges”)将切换该特定数据集。 这适用于所有图表类型。
Bar charts are (mostly) just line charts that look a bit different. By changing one line of our previous example, we can create a bar chart.
条形图(大多数情况下)只是折线图,看上去有些不同。 通过更改上一个示例中的一行,我们可以创建一个条形图。
type: 'line'
to:
至:
type: 'bar'
Yes, it’s really that easy.
是的,真的很容易。
See the Pen 2. Bar Chart by SitePoint (@SitePoint) on CodePen.
请参见CodePen上的Pen 2. Bar by SitePoint( @SitePoint ) 条形图 。
The full documentation on bar charts can be found here.
条形图的完整文档可以在这里找到。
Here’s the full code for this example:
这是此示例的完整代码:
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["M", "T", "W", "R", "F", "S", "S"],
datasets: [{
label: 'apples',
data: [12, 19, 3, 17, 28, 24, 7]
}, {
label: 'oranges',
data: [30, 29, 5, 5, 20, 3, 10]
}]
}
});
Radar charts are my favorite type, and again they are in the same family as line and bar charts. Radar charts are just line charts with a radial X axis opposed to a straight line. To get a quick radar chart, change:
雷达图是我最喜欢的类型,同样,它们与折线图和条形图属于同一个系列。 雷达图只是具有径向X轴与直线相对的折线图。 要获取快速雷达图,请更改:
type: 'bar'
to:
至:
type: 'radar'
Because that’s just how Chart.js rolls.
因为这就是Chart.js滚动的方式 。
Unfortunately, the result is a bit ugly and very hard to read. Bar charts don’t have overlap, so solid colors are beneficial. This is not the case with radar charts, which do leverage overlap. We can accommodate this by updating the opactity value of our backgroundColor
and adding a borderColor
.
不幸的是,结果有点难看并且很难阅读。 条形图没有重叠,因此纯色是有益的。 雷达图不是这种情况,因为雷达图确实会重叠。 我们可以通过更新我们的opactity值适应这种backgroundColor
和添加borderColor
。
{
label: 'apples',
backgroundColor: "rgba(179,11,198,.2)",
borderColor: "rgba(179,11,198,1)",
data: [12, 19, 3, 17, 6, 3, 7]
}
This adds a clearish background and lets us visualize the overlap.
这样可以增加背景的清晰度,并使我们可视化重叠部分。
See the Pen 3. Radar Charts by SitePoint (@SitePoint) on CodePen.
见笔3雷达图由SitePoint( @SitePoint上) CodePen 。
To read more about radar charts, check out the docs.
要了解有关雷达图的更多信息, 请查看docs 。
Here’s the full code from this example:
这是此示例中的完整代码:
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'radar',
data: {
labels: ["M", "T", "W", "T", "F", "S", "S"],
datasets: [{
label: 'apples',
backgroundColor: "rgba(153,255,51,0.4)",
borderColor: "rgba(153,255,51,1)",
data: [12, 19, 3, 17, 28, 24, 7]
}, {
label: 'oranges',
backgroundColor: "rgba(255,153,0,0.4)",
borderColor: "rgba(255,153,0,1)",
data: [30, 29, 5, 5, 20, 3, 10]
}]
}
});
Polar charts give each data point an equal amount of radial space. Segments with larger values extend further from the center of the graph. Here’s the polar chart for our apples
data set.
极坐标图为每个数据点提供相等的径向空间。 具有较大值的线段从图的中心进一步延伸。 这是apples
数据集的极坐标图。
See the Pen 4. Polar Charts by SitePoint (@SitePoint) on CodePen.
见笔4.极坐标图由SitePoint( @SitePoint上) CodePen 。
As usual, specifying that this is a polar chart can be done with a single line. Change:
像往常一样,可以用一条线来指定这是一个极坐标图。 更改:
type: 'radar'
to:
至:
type: 'polarArea'
But, the polar area is the first chart I’ve covered that can’t be used to compare two data sets. The previous examples were different ways of contrasting two arrays of equal length, whereas the polar chart (and pie chart, which will be covered next) only visualize a single group of numbers.
但是,极区是我所介绍的第一个图表,不能用来比较两个数据集。 前面的示例以不同的方式对比两个等长的数组,而极坐标图(以及饼图,将在下面介绍)仅可视化一组数字。
Here’s the full code for this example:
这是此示例的完整代码:
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'polarArea',
data: {
labels: ["M", "T", "W", "T", "F", "S", "S"],
datasets: [{
backgroundColor: [
"#2ecc71",
"#3498db",
"#95a5a6",
"#9b59b6",
"#f1c40f",
"#e74c3c",
"#34495e"
],
data: [12, 19, 3, 17, 28, 24, 7]
}]
}
});
The only new code is a backgroundColor
array. Each color matches with the data
element of the same index.
唯一的新代码是backgroundColor
数组。 每种颜色都与相同索引的data
元素匹配。
To read more about polar area charts, check out the docs.
要了解有关极地面积图的更多信息, 请查看docs 。
You can probably guess this part by now. Change:
您现在可能已经猜到这部分。 更改:
type: 'polarArea'
to:
至:
type: 'pie'
The type
property is the key to Chart.js. Remember how easy it was to transition from a line chart to bar and radar chart? Well, polar, pie, and doughnut charts are equally interchangeable. With that single change, we can alternate from a polar chart to a pie chart.
type
属性是Chart.js的关键。 还记得从折线图过渡到条形图和雷达图是多么容易吗? 极坐标图,饼图和甜甜圈图同样可以互换。 有了这一更改,我们就可以从极坐标图转换为饼图。
See the Pen 5. Pie Chart by SitePoint (@SitePoint) on CodePen.
请参见CodePen上的Pen 5.通过SitePoint( @SitePoint ) 创建的饼图 。
And for a Doughnut chart:
对于甜甜圈图:
type: 'pie'
to:
至:
type: 'doughnut'
See the Pen 6. Doughnut Chart by SitePoint (@SitePoint) on CodePen.
见笔6圆环图由SitePoint( @SitePoint上) CodePen 。
To read more about pie and doughnut charts, check out the docs.
要了解有关饼图和甜甜圈图的更多信息, 请查看docs 。
Here’s the full code for the pie chart:
这是饼图的完整代码:
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["M", "T", "W", "T", "F", "S", "S"],
datasets: [{
backgroundColor: [
"#2ecc71",
"#3498db",
"#95a5a6",
"#9b59b6",
"#f1c40f",
"#e74c3c",
"#34495e"
],
data: [12, 19, 3, 17, 28, 24, 7]
}]
}
});
Doughnut charts have an interesting property called cutoutPercentage
that dictates how big the center hole is. To dive into that, I first need to show you something about Chart.js I’ve ignored to help you speed through the basic chart types.
甜甜圈图具有一个有趣的属性,称为cutoutPercentage
,它指示中心Kong的大小。 为了深入探讨这一点,我首先需要向您展示一些有关Chart.js的内容,为了帮助您快速了解基本图表类型,我已将其忽略。
In every example so far, we’ve used the format:
到目前为止,在每个示例中,我们都使用以下格式:
var myChart = new Chart(ctx, {
type: //chart type,
data: // chart data
});
But there’s a third property called options
. It fits in right below data
.
但是还有第三个属性,叫做options
。 它正好位于data
下方。
var myChart = new Chart(ctx, {
type: //chart type,
data: // chart data,
options: // chart options
});
Now that you’re familiar with the fundamentals of Chart.js, it’s time to cover some of the tricks availible with options
.
现在,你已经熟悉了chart.js之基本面,它的时间来讨论一些与菱的招数options
。
It’s easy to add a title to any Chart.js chart by adding this set of options. Native titles are awesome, but it’s worth noting that they are mostly static and unchanging. This will matter when we try to add custom events in a minute.
通过添加这组选项,可以很容易地向任何Chart.js图表添加标题。 原生标题很棒,但值得注意的是它们大多是静态且不变的。 当我们尝试在一分钟内添加自定义事件时,这将很重要。
options: {
title: {
display: true,
text: 'Custom Chart Title'
}
}
The cutoutPercentage
property is a value from 0 to 50. Pie charts are just doughnut charts with a cutoutPercentage
of 0.
cutoutPercentage
属性的值为0到50。饼图只是cutoutPercentage
为0的甜甜圈图。
options: {
cutoutPercentage: 10,
}
If you would prefer that your bar charts were stacked, just add the following set of options into your bar chart code:
如果您希望堆叠条形图,只需将以下选项集添加到条形图代码中:
options: {
scales: {
yAxes: [{
stacked: true
}]
}
}
Each chart type has plenty of options for you to dig through. I encourage you to do so.
每种图表类型都有很多可供您选择的选项。 我鼓励你这样做。
As mentioned previously clicking on a legend will toggle the data set associated with that particular legend. Let’s augment that with our own functionality:
如前所述,单击图例将切换与该特定图例关联的数据集。 让我们用我们自己的功能来增强它:
var original = Chart.defaults.global.legend.onClick;
Chart.defaults.global.legend.onClick = function(e, legendItem) {
// Insert your custom functionality here
original.call(this, e, legendItem);
};
This code saves a reference to the legend item’s onClick
function into a variable called original
. It then overwrites this function with our own customized version. The e
parameter that we are passing to it is a reference to the click event that caused the function to fire and the legendItem
parameter is a reference to the legend that was clicked on. Once we’re done adding our own code, we call the original function specifying a this
value and passing through the parameters it is expecting. This results in the default action for clicking on a legend (toggling the data set) being carried out.
此代码将对图例项的onClick
函数的引用保存到名为original
的变量中。 然后,它将使用我们自己的自定义版本覆盖此功能。 我们传递给它的e
参数是对导致函数触发的click事件的引用, legendItem
参数是对所单击的图例的引用。 添加完自己的代码后,我们将调用原始函数,该函数指定this
值并传递期望的参数。 这导致单击图例(切换数据集)的默认操作被执行。
In other words, We can now package any functionality we want on top of the onClick()
call as long as we put it above original.call()
.
换句话说,我们现在可以将所需的任何功能打包在onClick()
调用之上,只要我们将其放在original.call()
之上即可。
Let’s augment our previous code so that when a user clicks on a legend, the caption at the bottom of the chart updates automatically.
让我们扩展前面的代码,以便当用户单击图例时,图表底部的标题会自动更新。
We are only changing the caption, but you can add any functionality you want. For example, a dashboard might have columns of the daily apples
and oranges
values. The dashboard could also dynamically update based on the status of your chart with the power of a custom callback. Creating interactive data is easy with Chart.js.
我们仅更改标题,但是您可以添加所需的任何功能。 例如,仪表板可能包含每日apples
和oranges
值的列。 仪表板还可以使用自定义回调的功能根据图表的状态动态更新。 使用Chart.js轻松创建交互式数据。
Here’s the code
这是代码
var labels = {
"apples": true,
"oranges": true
};
var caption = document.getElementById("caption");
var update_caption = function(legend) {
labels[legend.text] = legend.hidden;
var selected = Object.keys(labels).filter(function(key) {
return labels[key];
});
var text = selected.length ? selected.join(" & ") : "nothing";
caption.innerHTML = "The above chart displays " + text;
};
As you can see, we’re using an object literal to keep track of the status of the legends. We’re also taking advantage of the legend.text
and legend.hidden
properties to update its state. The filter function will return any of the object keys whose value is true
which we use to build our caption.
如您所见,我们使用对象文字来跟踪图例的状态。 我们还利用了legend.text
和legend.hidden
属性来更新其状态。 filter函数将返回任何值为true
的对象键,这些键用于构建标题。
See the Pen 7. Bar Chart with Custom onClick() by SitePoint (@SitePoint) on CodePen.
请参见笔7。CodePen上的SitePoint ( @SitePoint ) 具有自定义onClick()的条形图 。
This article has used Chart.js 2.0 syntax. Chart.js 2.0 is relatively new to 2016. The most obvious difference between 2.0 and 1.0 being how to declare charts.
本文使用了Chart.js 2.0语法。 Chart.js 2.0在2016年相对较新。2.0和1.0之间最明显的区别是如何声明图表。
1.0
1.0
var LineChartDemo = new Chart(ctx).Line(
//data here,
//options here
);
2.0
2.0
var myChart = new Chart(ctx, {
type: 'line',
data: //data here,
options: //options here
}
Version 1.0 focuses on using function chaining to create a specific type of chart, and then passing in data and options. Version 2.0 switches this up by letting the user create a generic chart object and then pass in type as well as data and options. The second approach matches up more with the philosophy of Chart.js by being as modular and individual as possible. It’s worth noting Chart.js 2.0 is backwards compatible and still accepts 1.0 syntax.
1.0版专注于使用函数链来创建特定类型的图表,然后传递数据和选项。 2.0版通过允许用户创建一个通用图表对象然后传递类型以及数据和选项来对此进行切换。 第二种方法尽可能地模块化和个性化,从而更符合Chart.js的理念。 值得注意的是,Chart.js 2.0向后兼容,但仍接受1.0语法。
Another key feature of Chart.js 2.0 is mobile support. Charts can now scale to fit mobile screens and handle touch events on mobile browsers. With the current proliferation of mobile devices, this is a must-have feature for websites in 2016.
Chart.js 2.0的另一个主要功能是移动支持。 图表现在可以缩放以适合移动屏幕并处理移动浏览器上的触摸事件。 随着当前移动设备的激增,这是2016年网站的必备功能。
Another feature new to 2.0 that we used in this guide is title
. Charts now have integrated titles that will cooperate with the chart they’re attached to.
我们在本指南中使用的2.0新增功能是title
。 图表现在具有集成的标题,可以与其所附的图表配合使用。
The full list of updates can be found in the 2.0.0 release notes.
更新的完整列表可以在2.0.0发行说明中找到 。
Chart.js is a perfect match for rapid prototyping of simple charts. There are eight main chart types, of which we have covered: line
, bar
, radar
, polarArea
, pie
and doughnut
. These diverse charts cover most common ways to visualize data, meaning that Chart.js is probably the only graphing library you’ll need for your next project.
Chart.js非常适合简单图表的快速原型制作。 共有八种主要的图表类型,我们涵盖了它们: line
, bar
, radar
, polarArea
, pie
和doughnut
。 这些多样化的图表涵盖了可视化数据的最常用方法,这意味着Chart.js可能是您下一个项目所需的唯一图形库。
If you want to learn more about Chart.js, I highly recommend the docs, which you can find on the Chart.js website. If you have any questions or comments, I’d love to hear them below.
如果您想了解有关Chart.js的更多信息,我强烈建议您在Chart.js网站上找到这些文档 。 如果您有任何疑问或意见,欢迎在下面听到。
翻译自: https://www.sitepoint.com/introduction-chart-js-2-0-six-examples/
chart.min.js