前端開發者常用的9個JavaScript圖表庫
當前,資料視覺化已經成為資料科學領域非常重要的一部分。不同網路系統中產生的資料,都需要經過適當的視覺化處理,以便更好的呈現給使用者讀取和分析。
對任何一個組織來說,如果能夠充分的獲取資料、視覺化資料和分析資料,那麼就能很大程度上幫助瞭解資料產生的深層次原因,以便據此做出正確的決定。
對於前端開發人員來說,如果能夠掌握互動式網頁中的資料視覺化技術,則是一項很棒的技能。當然,通過一些 JavaScript 的圖表庫也會使前端的資料視覺化變得更加容易。使用這些庫,開發者可以在無需考慮不同的語法所帶來的程式設計難題的情況下,輕鬆實現將資料轉化為易於理解的圖表。
下面是挑選出的9個 JavaScript 圖表庫:
- Chart.js
- Chartist
- FlexChart
- Echarts
- NVD3
- C3.js
- TauCharts
- ReCharts
- Flot
ofollow,noindex">Chart.js

image.png
Chart.js 是一種簡潔、使用者友好的圖表庫,同時也是基於 HTML5 的 JavaScript 庫,用於建立動畫、互動式和可自定義的圖表和圖形。
藉助 Chart.js,使用者可以輕鬆直觀地檢視混合圖表型別。預設情況下,也可以使用 Chart.js 建立響應式網頁。
Chart.js 庫允許使用者快速建立視覺化資料。Chart.js 易於設定,對初學者十分友好。使用 Chart.js 則不必考慮瀏覽器的相容性問題,因為 Chart.js 支援舊瀏覽器。
使用 npm 安裝 Chart.js:
npm install chart.js --save
Chart.js 繪製雷達圖的程式碼示例:
const ctx = document.getElementById("myChart");
const options = {
scale: {
// Hides the scale
}
};
const data = {
labels: ['Running', 'Swimming', 'Eating', 'Cycling'],
datasets: [
{
data: [-10, -5, -3, -15],
label: "two",
borderColor: '#ffc63b'
},
{
data: [10, 5, 3, 10],
label: "three",
borderColor: '#1d9a58'
},
{
data: [18, 10, 4, 2],
label: "one",
borderColor: '#d8463c'
},
]
}
const myRadarChart = new Chart(ctx, {
data: data,
type: 'radar',
options: options
});
Chartist

image.png
Chartist 庫很適合於建立美觀、響應能力強、閱讀友好的圖表。Chartist 使用 SVG 來呈現圖表。
Chartist 還提供了使用 CSS 媒體查詢和創意動畫來自定義圖表的能力。使用者使用 Chartist 在圖表設計中實現自己的所有創意。
Chartist 易於配置,也易於使用 Sass 進行定製。但是,它不支援舊瀏覽器。
使用 Chartist,可以通過 CSS 的樣式來美化你的 SVG,使用者完全可以現實自己所想的所有圖表樣式。
使用 npm 安裝 Chartist:
npm install chartist --save
Chartist 建立具有自定義標籤的餅圖的程式碼示例:
var data = {
labels: ['Bananas', 'Apples', 'Grapes'],
series: [20, 15, 40]
};
var options = {
labelInterpolationFnc: function(value) {
return value[0]
}
};
var responsiveOptions = [
['screen and (min-width: 640px)', {
chartPadding: 30,
labelOffset: 130,
labelDirection: 'explode',
labelInterpolationFnc: function(value) {
return value;
}
}],
['screen and (min-width: 1024px)', {
labelOffset: 80,
chartPadding: 20
}]
];
new Chartist.Pie('.ct-chart', data, options, responsiveOptions);

image.png
FlexChart 是高效能的圖表工具。使用 FlexChart,可輕鬆的將表格資料視覺化為業務圖表。FlexChart 不但支援常見的圖表型別,如折線圖、餅狀圖、面積圖等,還支援氣泡圖、K線圖、條形圖、漏斗圖等高階圖表型別。
FlexChart 的使用也十分簡單,FlexChart 圖表將所有與資料有關的任務都委託給 CollectionView 類,只需操作 CollectionView 類,就能實現過濾、排序和分組資料等功能。
FlexChart 包含的圖表元素也比較全面,如圖表圖例、圖表標題、圖表頁尾、數軸、圖表 series 和標籤等,使用者也可以為圖表新增自定義的元素,如平均線和趨勢線等。
FlexChart 本質上是一種互動式的圖表,不論是資料進行任何的更改,都會自動反應在圖表上,如圖表曲線隨資料放大縮小、過濾、鑽取、動畫等。
檢視 FlexChart 的 中文學習指南 和 旭日圖Demo 。
FlexChart 繪製柱狀圖的程式碼示例:
onload = function() {
// wrap data in a CollectionView so the grid and chart
// get notifications
var data = new wijmo.collections.CollectionView(getData());
// create the chart
var theChart = new wijmo.chart.FlexChart('#theChart', {
itemsSource: data,
bindingX: 'country',
series: [
{ binding: 'sales', name: 'Sales' },
{ binding: 'expenses', name: 'Expenses' },
{ binding: 'downloads', name: 'Downloads' }
]
})
// create a grid to show the data
var theGrid = new wijmo.grid.FlexGrid('#theGrid', {
itemsSource: data
})
// create some random data
function getData() {
var countries = 'US,Germany,UK,Japan,Italy,Greece'.split(','),
data = [];
for (var i = 0; i < countries.length; i++) {
data.push({
country: countries[i],
sales: Math.random() * 10000,
expenses: Math.random() * 5000,
downloads: Math.round(Math.random() * 20000),
});
}
return data;
}
}
Echarts

image.png
Echarts 是網頁的資料視覺化方面的一個非常有用的庫。使用 Echarts,開發者可以建立直觀的、可自定義的互動式圖表,讓資料的展示和分析變得十分容易。
由於 Echarts 是用普通的 JavaScript 編寫的,所以 Echarts 不存在其它圖表庫存在的無法無縫遷移的問題。
同時,Echarts 也提供了很多官方文件供使用者檢視。
使用 npm 可以很容易的完成 Echarts 的安裝:
npm install echarts --save
Echarts 繪製散點圖程式碼示例:
var dom = document.getElementById("container");
var myChart = echarts.init(dom);
var app = {};
option = null;
option = {
title: {
text: 'Large-scale scatterplot'
},
tooltip : {
trigger: 'axis',
showDelay : 0,
axisPointer:{
show: true,
type : 'cross',
lineStyle: {
type : 'dashed',
width : 1
}
},
zlevel: 1
},
legend: {
data:['sin','cos']
},
toolbox: {
show : true,
feature : {
mark : {show: true},
dataZoom : {show: true},
dataView : {show: true, readOnly: false},
restore : {show: true},
saveAsImage : {show: true}
}
},
xAxis : [
{
type : 'value',
scale:true
}
],
yAxis : [
{
type : 'value',
scale:true
}
],
series : [
{
name:'sin',
type:'scatter',
large: true,
symbolSize: 3,
data: (function () {
var d = [];
var len = 10000;
var x = 0;
while (len--) {
x = (Math.random() * 10).toFixed(3) - 0;
d.push([
x,
//Math.random() * 10
(Math.sin(x) - x * (len % 2 ? 0.1 : -0.1) * Math.random()).toFixed(3) - 0
]);
}
//console.log(d)
return d;
})()
},
{
name:'cos',
type:'scatter',
large: true,
symbolSize: 2,
data: (function () {
var d = [];
var len = 20000;
var x = 0;
while (len--) {
x = (Math.random() * 10).toFixed(3) - 0;
d.push([
x,
//Math.random() * 10
(Math.cos(x) - x * (len % 2 ? 0.1 : -0.1) * Math.random()).toFixed(3) - 0
]);
}
//console.log(d)
return d;
})()
}
]
};
;
if (option && typeof option === "object") {
myChart.setOption(option, true);
}
NVD3

image
NVD3 是由 Mike Bostock 撰寫的基於 D3 的 JavaScript 庫。NVD3 允許使用者在 Web 應用程式中建立美觀的、可複用的圖表。
NVD3 具有很強大的圖表功能,能夠很方便的建立箱形圖、旭日形和燭臺圖等。如果使用者想在 JavaScript 圖表庫中用到大量的能力,推薦試用 NVD3
NVD3 圖表庫的速度有時可能會成為一個問題,與 Fastdom 安裝配合使用,速度會更快。
NVD3 繪製簡單的折線圖程式碼示例:
<pre style="box-sizing: inherit; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 16px; white-space: pre-wrap; overflow: auto; border-radius: 3px; padding: 2px; line-height: 1.4; word-wrap: normal; display: block; background: rgb(63, 63, 63); color: rgb(220, 220, 220); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">/*These lines are all chart setup. Pick and choose which chart features you want to utilize. */
nv.addGraph(function() {
var chart = nv.models.lineChart()
.margin({left: 100}) //Adjust chart margins to give the x-axis some breathing room.
.useInteractiveGuideline(true) //We want nice looking tooltips and a guideline!
.transitionDuration(350) //how fast do you want the lines to transition?
.showLegend(true) //Show the legend, allowing users to turn on/off line series.
.showYAxis(true) //Show the y-axis
.showXAxis(true) //Show the x-axis
;
chart.xAxis //Chart x-axis settings
.axisLabel('Time (ms)')
.tickFormat(d3.format(',r'));
chart.yAxis //Chart y-axis settings
.axisLabel('Voltage (v)')
.tickFormat(d3.format('.02f'));
/* Done setting the chart up? Time to render it!*/
var myData = sinAndCos(); //You need data...
d3.select('#chart svg') //Select the <svg> element you want to render the chart in.
.datum(myData) //Populate the <svg> element with chart data...
.call(chart); //Finally, render the chart!
//Update the chart when window resizes.
nv.utils.windowResize(function() { chart.update() });
return chart;
});
/**************************************
-
Simple test data generator
*/
function sinAndCos() {
var sin = [],sin2 = [],
cos = [];
//Data is represented as an array of {x,y} pairs.
for (var i = 0; i < 100; i++) {
sin.push({x: i, y: Math.sin(i/10)});
sin2.push({x: i, y: Math.sin(i/10) *0.25 + 0.5});
cos.push({x: i, y: .5 * Math.cos(i/10)});
}
//Line chart data should be sent as an array of series objects.
return [
{
values: sin, //values - represents the array of {x,y} data points
key: 'Sine Wave', //key - the name of the series.
color: '#ff7f0e' //color - optional: choose your own line color.
},
{
values: cos,
key: 'Cosine Wave',
color: '#2ca02c'
},
{
values: sin2,
key: 'Another sine wave',
color: '#7777ff',
area: true //area - set to true if you want this line to turn into a filled area chart.
}
];
}</pre>
C3.js

image
與 TauCharts 相同,C3.js 也是一個非常有效的基於 D3 的圖表視覺化庫。另外,C3.js 允許使用者建立可定製的具有個人風格的類。
C3.js 看起來是個比較難的庫,但是一旦掌握了 C3.js 技巧,就能得心應手的使用了。
有了 C3.js 圖表庫,即使在第一次渲染之後,使用者也可以通過建立回撥來更新圖表。C3.js 也允許使用者為自己的 Web 應用程式建立可複用的圖表,從而減少工作量。
使用 npm 安裝 C3.js 圖表庫:
npm install c3
C3.js 繪製組合圖的程式碼示例:
<pre style="box-sizing: inherit; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 16px; white-space: pre-wrap; overflow: auto; border-radius: 3px; padding: 2px; line-height: 1.4; word-wrap: normal; display: block; background: rgb(63, 63, 63); color: rgb(220, 220, 220); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">var chart = c3.generate({
data: {
columns: [
['data1', 30, 20, 50, 40, 60, 50],
['data2', 200, 130, 90, 240, 130, 220],
['data3', 300, 200, 160, 400, 250, 250],
['data4', 200, 130, 90, 240, 130, 220],
['data5', 130, 120, 150, 140, 160, 150],
['data6', 90, 70, 20, 50, 60, 120],
],
type: 'bar',
types: {
data3: 'spline',
data4: 'line',
data6: 'area',
},
groups: [
['data1','data2']
]
}
});</pre>
TauCharts

image
TauCharts 是最靈活的 JavaScript 圖表庫之一。它是基於 D3 建立的,是一個以資料為中心的 JavaScript 圖表庫,可以改進資料視覺化的效果。
TauCharts 十分靈活,訪問其 API 也十分輕鬆。TauCharts 為使用者提供了無縫對映和視覺化的資料,使用 TauCharts 能夠設計出十分美觀的資料介面。同時,TauCharts 也和易於學習。
通過 npm 安裝 TauCharts:
npm install taucharts
TauCharts 繪製水平線的程式碼示例:
<pre style="box-sizing: inherit; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 16px; white-space: pre-wrap; overflow: auto; border-radius: 3px; padding: 2px; line-height: 1.4; word-wrap: normal; display: block; background: rgb(63, 63, 63); color: rgb(220, 220, 220); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">var defData = [
{"team": "d", "cycleTime": 1, "effort": 1, "count": 1, "priority": "low"}, {
"team": "d",
"cycleTime": 2,
"effort": 2,
"count": 5,
"priority": "low"
}, {"team": "d", "cycleTime": 3, "effort": 3, "count": 8, "priority": "medium"}, {
"team": "d",
"cycleTime": 4,
"effort": 4,
"count": 3,
"priority": "high"
}, {"team": "l", "cycleTime": 2, "effort": 1, "count": 1, "priority": "low"}, {
"team": "l",
"cycleTime": 3,
"effort": 2,
"count": 5,
"priority": "low"
}, {"team": "l", "cycleTime": 4, "effort": 3, "count": 8, "priority": "medium"}, {
"team": "l",
"cycleTime": 5,
"effort": 4,
"count": 3,
"priority": "high"
},
{"team": "k", "cycleTime": 2, "effort": 4, "count": 1, "priority": "low"}, {
"team": "k",
"cycleTime": 3,
"effort": 5,
"count": 5,
"priority": "low"
}, {"team": "k", "cycleTime": 4, "effort": 6, "count": 8, "priority": "medium"}, {
"team": "k",
"cycleTime": 5,
"effort": 8,
"count": 3,
"priority": "high"
}];
var chart = new tauCharts.Chart({
data: defData,
type: 'horizontalBar',
x: 'effort',
y: 'team',
color:'priority'
});
chart.renderTo('#bar');</pre>
Recharts

image
ReCharts 是一個使用 React 構建的,基於 D3 的圖表庫。
使用 ReCharts,使用者可以在 React Web 應用程式中無縫地編寫圖表。
Recharts 非常輕巧,並使用 SVG 元素來建立很奇特的圖表。
使用 npm 安裝 Recharts:
npm install recharts
Recharts 沒有冗長的文件,它很直接。當你遇到困難時,使用 Recharts 可以很容易找到解決方案。
Recharts 建立自定義內容樹圖的程式碼示例:
<pre style="box-sizing: inherit; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 16px; white-space: pre-wrap; overflow: auto; border-radius: 3px; padding: 2px; line-height: 1.4; word-wrap: normal; display: block; background: rgb(63, 63, 63); color: rgb(220, 220, 220); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">const {Treemap} = Recharts;
const data = [
{
name: 'axis',
children: [
{ name: 'Axes', size: 1302 },
{ name: 'Axis', size: 24593 },
{ name: 'AxisGridLine', size: 652 },
{ name: 'AxisLabel', size: 636 },
{ name: 'CartesianAxes', size: 6703 },
],
},
{
name: 'controls',
children: [
{ name: 'AnchorControl', size: 2138 },
{ name: 'ClickControl', size: 3824 },
{ name: 'Control', size: 1353 },
{ name: 'ControlList', size: 4665 },
{ name: 'DragControl', size: 2649 },
{ name: 'ExpandControl', size: 2832 },
{ name: 'HoverControl', size: 4896 },
{ name: 'IControl', size: 763 },
{ name: 'PanZoomControl', size: 5222 },
{ name: 'SelectionControl', size: 7862 },
{ name: 'TooltipControl', size: 8435 },
],
},
{
name: 'data',
children: [
{ name: 'Data', size: 20544 },
{ name: 'DataList', size: 19788 },
{ name: 'DataSprite', size: 10349 },
{ name: 'EdgeSprite', size: 3301 },
{ name: 'NodeSprite', size: 19382 },
{
name: 'render',
children: [
{ name: 'ArrowType', size: 698 },
{ name: 'EdgeRenderer', size: 5569 },
{ name: 'IRenderer', size: 353 },
{ name: 'ShapeRenderer', size: 2247 },
],
},
{ name: 'ScaleBinding', size: 11275 },
{ name: 'Tree', size: 7147 },
{ name: 'TreeBuilder', size: 9930 },
],
},
{
name: 'layout',
children: [
{ name: 'AxisLayout', size: 6725 },
{ name: 'BundledEdgeRouter', size: 3727 },
{ name: 'CircleLayout', size: 9317 },
{ name: 'CirclePackingLayout', size: 12003 },
{ name: 'DendrogramLayout', size: 4853 },
{ name: 'ForceDirectedLayout', size: 8411 },
{ name: 'IcicleTreeLayout', size: 4864 },
{ name: 'IndentedTreeLayout', size: 3174 },
{ name: 'Layout', size: 7881 },
{ name: 'NodeLinkTreeLayout', size: 12870 },
{ name: 'PieLayout', size: 2728 },
{ name: 'RadialTreeLayout', size: 12348 },
{ name: 'RandomLayout', size: 870 },
{ name: 'StackedAreaLayout', size: 9121 },
{ name: 'TreeMapLayout', size: 9191 },
],
},
{ name: 'Operator', size: 2490 },
{ name: 'OperatorList', size: 5248 },
{ name: 'OperatorSequence', size: 4190 },
{ name: 'OperatorSwitch', size: 2581 },
{ name: 'SortOperator', size: 2023 },
],
}
];
const COLORS = ['#8889DD', '#9597E4', '#8DC77B', '#A5D297', '#E2CF45', '#F8C12D'];
const CustomizedContent = React.createClass({
render() {
const { root, depth, x, y, width, height, index, payload, colors, rank, name } = this.props;
return (
<g>
<rect
x={x}
y={y}
width={width}
height={height}
style={{
fill: depth < 2 ? colors[Math.floor(index / root.children.length * 6)] : 'none',
stroke: '#fff',
strokeWidth: 2 / (depth + 1e-10),
strokeOpacity: 1 / (depth + 1e-10),
}}
/>
{
depth === 1 ?
<text
x={x + width / 2}
y={y + height / 2 + 7}
textAnchor="middle"
fill="#fff"
fontSize={14}
>
{name}
</text>
: null
}
{
depth === 1 ?
<text
x={x + 4}
y={y + 18}
fill="#fff"
fontSize={16}
fillOpacity={0.9}
>
{index + 1}
</text>
: null
}
</g>
);
}
});
const SimpleTreemap = React.createClass({
render () {
return (
<Treemap
width={400}
height={200}
data={data}
dataKey="size"
ratio={4/3}
stroke="#fff"
fill="#8884d8"
content={<CustomizedContent colors={COLORS}/>}
/>
);
}
})
ReactDOM.render(
<SimpleTreemap />,
document.getElementById('container')
);</pre>
Flot
image

image
目前,jQuery 已經成為 Web 開發人員非常重要的工具。有了 Flot.js,前端設計也變得更加容易。
Flot.js 是 JavaScript 庫中較為古老的圖表庫之一。儘管如此,Flot.js 也不會因為繪製折線圖、餅圖、條形圖、面積圖、甚至堆疊圖表而降低其效能。
Flot.js 有一個很完善的文件。當用戶遇到困難時,可以很容易地找到解決辦法。Flot.js 也支援舊版本的瀏覽器。
可以選擇不使用 npm 來安裝 Flot.js,而是在 HTML5 中包含 jQuery 和 JavaScript 檔案。
Flot.js 的基本用法程式碼示例:
<pre style="box-sizing: inherit; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 16px; white-space: pre-wrap; overflow: auto; border-radius: 3px; padding: 2px; line-height: 1.4; word-wrap: normal; display: block; background: rgb(63, 63, 63); color: rgb(220, 220, 220); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">$(function () {
var d1 = [];
for (var i = 0; i < 14; i += 0.5)
d1.push([i, Math.sin(i)]);
var d2 = [[0, 3], [4, 8], [8, 5], [9, 13]]; // a null signifies separate line segments var d3 = [[0, 12], [7, 12], null, [7, 2.5], [12, 2.5]]; $.plot($("#placeholder"), [ d1, d2, d3 ]);
});</pre>
JavaScript 開發工具推薦
SpreadJS 純前端表格控制元件是基於 HTML5 的 JavaScript 電子表格和網格功能控制元件,提供了完備的公式引擎、排序、過濾、輸入控制元件、資料視覺化、Excel 匯入/匯出等功能,適用於 .NET、Java 和移動端等各平臺線上編輯類 Excel 功能的表格程式開發。
總結
以上介紹的 JavaScript 庫都是高質量的圖表庫。但是在學習這些庫的過程中,可能會因為學習曲線陡峭或是缺乏學習資料而遇到困難,一種很好的方案是將這些庫結合起來使用。最後也歡迎大家補充更多的 JavaScript 圖表庫。