ホームページ  >  記事  >  ウェブフロントエンド  >  9つのJavaScriptチャートライブラリを詳しく解説

9つのJavaScriptチャートライブラリを詳しく解説

小云云
小云云オリジナル
2017-12-20 10:09:091853ブラウズ

現在、データの視覚化はデータサイエンスの分野で非常に重要な部分となっています。さまざまなネットワーク システムで生成されたデータは、ユーザーが読み取ったり分析したりできるように、適切に視覚化する必要があります。この記事では主に 9 つの JavaScript チャート ライブラリとその使い方について詳しく説明します。必要な方はぜひ参考にしてください。

どのような組織でも、データを完全に取得し、データを視覚化し、データを分析できれば、データ生成の根深い理由を理解し、それに応じて正しい意思決定を行うことができるようになります。

フロントエンド開発者にとって、インタラクティブな Web ページでデータ視覚化テクニックを習得できることは素晴らしいスキルです。もちろん、フロントエンドのデータ視覚化も、いくつかの JavaScript チャート ライブラリを通じて簡単になります。これらのライブラリを使用すると、開発者はさまざまな構文によるプログラミングの課題を考慮することなく、データをわかりやすいグラフに簡単に変換できます。

ここでは 9 つの厳選された JavaScript チャート ライブラリを紹介します:

Chart.js Chartist FlexChart Echarts NVD3 C3.js TauCharts ReCharts Flot

Chart.js

Char t.js は単純です、アニメーション化されたインタラクティブでカスタマイズ可能なチャートとグラフを作成するための、ユーザーフレンドリーなチャート ライブラリと HTML5 ベースの JavaScript ライブラリ。

Chart.js を使用すると、ユーザーは混合チャート タイプを簡単かつ直感的に表示できます。デフォルトでは、Chart.js を使用してレスポンシブ Web ページを作成することもできます。

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

チャーティスト図書館美しく、応答性が高く、読みやすいグラフを作成するのに最適です。 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);

FlexChart

FlexChart は高パフォーマンスのグラフ作成ですツール。 FlexChart を使用すると、表形式のデータをビジネス グラフに簡単に視覚化できます。 FlexChart は、折れ線グラフ、円グラフ、面グラフなどの一般的なグラフ タイプをサポートするだけでなく、バ​​ブル チャート、K 折れ線グラフ、棒グラフ、ファネル チャートなどの高度なグラフ タイプもサポートします。

FlexChart の使用も非常に簡単です。FlexChart チャートは、データ関連のすべてのタスクを CollectionView クラスに委任するだけで、データのフィルタリング、並べ替え、グループ化などの機能を実装できます。

FlexChart には、チャートの凡例、チャートのタイトル、チャートのフッター、数値軸、チャートのシリーズとラベルなどの包括的なチャート要素も含まれています。ユーザーは、平均線や傾向線などのカスタム要素をチャートに追加することもできます。

FlexChart は基本的にインタラクティブなチャートであり、チャート曲線のズームイン、ズームアウト、フィルタリング、ドリル、アニメーションなどのデータへの変更がデータとともに自動的にチャートに反映されます。

FlexChart の中国語学習ガイドとサンバースト チャートのデモをご覧ください。ヒストグラムを描画するための

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

Echarts は、Web ページ上のデータ視覚化に非常に便利なライブラリです。 Echarts を使用すると、開発者はデータの表示と分析を容易にする直感的でカスタマイズ可能な対話型チャートを作成できます。

Echarts は通常の JavaScript で書かれているため、他のチャート ライブラリにあるシームレスな移行の問題はありません。

同時に、Echarts はユーザーが閲覧できる多くの公式ドキュメントも提供します。

Echarts のインストールは、npm を使用して簡単に完了できます:

npm install echarts --save

Echarts 散布図のコード例:


var dom = document.getElementById("container");
var myChart = echarts.init(dom);
var app = {};
option = null;
option = {
 title: {
 text: &#39;Large-scale scatterplot&#39;
 },
 tooltip : {
 trigger: &#39;axis&#39;,
 showDelay : 0,
 axisPointer:{
  show: true,
  type : &#39;cross&#39;,
  lineStyle: {
  type : &#39;dashed&#39;,
  width : 1
  }
 },
 zlevel: 1
 },
 legend: {
 data:[&#39;sin&#39;,&#39;cos&#39;]
 },
 toolbox: {
 show : true,
 feature : {
  mark : {show: true},
  dataZoom : {show: true},
  dataView : {show: true, readOnly: false},
  restore : {show: true},
  saveAsImage : {show: true}
 }
 },
 xAxis : [
 {
  type : &#39;value&#39;,
  scale:true
 }
 ],
 yAxis : [
 {
  type : &#39;value&#39;,
  scale:true
 }
 ],
 series : [
 {
  name:&#39;sin&#39;,
  type:&#39;scatter&#39;,
  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:&#39;cos&#39;,
  type:&#39;scatter&#39;,
  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

NVD3 是由 Mike Bostock 撰写的基于 D3 的 JavaScript 库。NVD3 允许用户在 Web 应用程序中创建美观的、可复用的图表。

NVD3 具有很强大的图表功能,能够很方便的创建箱形图、旭日形和烛台图等。如果用户想在 JavaScript 图表库中用到大量的能力,推荐试用 NVD3

NVD3 图表库的速度有时可能会成为一个问题,与 Fastdom 安装配合使用,速度会更快。

NVD3 绘制简单的折线图代码示例:


/*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(&#39;Time (ms)&#39;)
 .tickFormat(d3.format(&#39;,r&#39;));

 chart.yAxis //Chart y-axis settings
 .axisLabel(&#39;Voltage (v)&#39;)
 .tickFormat(d3.format(&#39;.02f&#39;));

 /* Done setting the chart up? Time to render it!*/
 var myData = sinAndCos(); //You need data...

 d3.select(&#39;#chart svg&#39;) //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: &#39;Sine Wave&#39;, //key - the name of the series.
 color: &#39;#ff7f0e&#39; //color - optional: choose your own line color.
 },
 {
 values: cos,
 key: &#39;Cosine Wave&#39;,
 color: &#39;#2ca02c&#39;
 },
 {
 values: sin2,
 key: &#39;Another sine wave&#39;,
 color: &#39;#7777ff&#39;,
 area: true //area - set to true if you want this line to turn into a filled area chart.
 }
 ];
}

C3.js

与 TauCharts 相同,C3.js 也是一个非常有效的基于 D3 的图表可视化库。另外,C3.js 允许用户创建可定制的具有个人风格的类。

C3.js 看起来是个比较难的库,但是一旦掌握了 C3.js 技巧,就能得心应手的使用了。

有了 C3.js 图表库,即使在第一次渲染之后,用户也可以通过创建回调来更新图表。C3.js 也允许用户为自己的 Web 应用程序创建可复用的图表,从而减少工作量。

使用 npm 安装 C3.js 图表库:

npm install c3

C3.js 绘制组合图的代码示例:


var chart = c3.generate({
 data: {
 columns: [
  [&#39;data1&#39;, 30, 20, 50, 40, 60, 50],
  [&#39;data2&#39;, 200, 130, 90, 240, 130, 220],
  [&#39;data3&#39;, 300, 200, 160, 400, 250, 250],
  [&#39;data4&#39;, 200, 130, 90, 240, 130, 220],
  [&#39;data5&#39;, 130, 120, 150, 140, 160, 150],
  [&#39;data6&#39;, 90, 70, 20, 50, 60, 120],
 ],
 type: &#39;bar&#39;,
 types: {
  data3: &#39;spline&#39;,
  data4: &#39;line&#39;,
  data6: &#39;area&#39;,
 },
 groups: [
  [&#39;data1&#39;,&#39;data2&#39;]
 ]
 }
});

TauCharts

TauCharts 是最灵活的 JavaScript 图表库之一。它是基于 D3 创建的,是一个以数据为中心的 JavaScript 图表库,可以改进数据可视化的效果。

TauCharts 十分灵活,访问其 API 也十分轻松。TauCharts 为用户提供了无缝映射和可视化的数据,使用 TauCharts 能够设计出十分美观的数据界面。同时,TauCharts 也和易于学习。

通过 npm 安装 TauCharts:

npm install taucharts

TauCharts 绘制水平线的代码示例:


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: &#39;horizontalBar&#39;,  
  x: &#39;effort&#39;,
  y: &#39;team&#39;,
  color:&#39;priority&#39;
 });
chart.renderTo(&#39;#bar&#39;);

Recharts

ReCharts 是一个使用 React 构建的,基于 D3 的图表库。

使用 ReCharts,用户可以在 React Web 应用程序中无缝地编写图表。

Recharts 非常轻巧,并使用 SVG 元素来创建很奇特的图表。

使用 npm 安装 Recharts:

npm install recharts

Recharts 没有冗长的文档,它很直接。当你遇到困难时,使用 Recharts 可以很容易找到解决方案。

Recharts 创建自定义内容树图的代码示例:


const {Treemap} = Recharts;

const data = [
  {
  name: &#39;axis&#39;,
  children: [
  { name: &#39;Axes&#39;, size: 1302 },
  { name: &#39;Axis&#39;, size: 24593 },
  { name: &#39;AxisGridLine&#39;, size: 652 },
  { name: &#39;AxisLabel&#39;, size: 636 },
  { name: &#39;CartesianAxes&#39;, size: 6703 },
  ],
  },
  {
  name: &#39;controls&#39;,
  children: [
  { name: &#39;AnchorControl&#39;, size: 2138 },
  { name: &#39;ClickControl&#39;, size: 3824 },
  { name: &#39;Control&#39;, size: 1353 },
  { name: &#39;ControlList&#39;, size: 4665 },
  { name: &#39;DragControl&#39;, size: 2649 },
  { name: &#39;ExpandControl&#39;, size: 2832 },
  { name: &#39;HoverControl&#39;, size: 4896 },
  { name: &#39;IControl&#39;, size: 763 },
  { name: &#39;PanZoomControl&#39;, size: 5222 },
  { name: &#39;SelectionControl&#39;, size: 7862 },
  { name: &#39;TooltipControl&#39;, size: 8435 },
  ],
  },
  {
  name: &#39;data&#39;,
  children: [
  { name: &#39;Data&#39;, size: 20544 },
  { name: &#39;DataList&#39;, size: 19788 },
  { name: &#39;DataSprite&#39;, size: 10349 },
  { name: &#39;EdgeSprite&#39;, size: 3301 },
  { name: &#39;NodeSprite&#39;, size: 19382 },
  {
  name: &#39;render&#39;,
  children: [
   { name: &#39;ArrowType&#39;, size: 698 },
   { name: &#39;EdgeRenderer&#39;, size: 5569 },
   { name: &#39;IRenderer&#39;, size: 353 },
   { name: &#39;ShapeRenderer&#39;, size: 2247 },
  ],
  },
  { name: &#39;ScaleBinding&#39;, size: 11275 },
  { name: &#39;Tree&#39;, size: 7147 },
  { name: &#39;TreeBuilder&#39;, size: 9930 },
  ],
  },
  {
  name: &#39;layout&#39;,
  children: [
   { name: &#39;AxisLayout&#39;, size: 6725 },
   { name: &#39;BundledEdgeRouter&#39;, size: 3727 },
   { name: &#39;CircleLayout&#39;, size: 9317 },
   { name: &#39;CirclePackingLayout&#39;, size: 12003 },
   { name: &#39;DendrogramLayout&#39;, size: 4853 },
   { name: &#39;ForceDirectedLayout&#39;, size: 8411 },
   { name: &#39;IcicleTreeLayout&#39;, size: 4864 },
   { name: &#39;IndentedTreeLayout&#39;, size: 3174 },
   { name: &#39;Layout&#39;, size: 7881 },
   { name: &#39;NodeLinkTreeLayout&#39;, size: 12870 },
   { name: &#39;PieLayout&#39;, size: 2728 },
   { name: &#39;RadialTreeLayout&#39;, size: 12348 },
   { name: &#39;RandomLayout&#39;, size: 870 },
   { name: &#39;StackedAreaLayout&#39;, size: 9121 },
   { name: &#39;TreeMapLayout&#39;, size: 9191 },
  ],
  },
  { name: &#39;Operator&#39;, size: 2490 },
  { name: &#39;OperatorList&#39;, size: 5248 },
  { name: &#39;OperatorSequence&#39;, size: 4190 },
  { name: &#39;OperatorSwitch&#39;, size: 2581 },
  { name: &#39;SortOperator&#39;, size: 2023 },
  ],
  }
 ];
const COLORS = [&#39;#8889DD&#39;, &#39;#9597E4&#39;, &#39;#8DC77B&#39;, &#39;#A5D297&#39;, &#39;#E2CF45&#39;, &#39;#F8C12D&#39;];
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)] : &#39;none&#39;,
  stroke: &#39;#fff&#39;,
  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')
);

Flot

目前,jQuery 已经成为 Web 开发人员非常重要的工具。有了 Flot.js,前端设计也变得更加容易。

Flot.js 是 JavaScript 库中较为古老的图表库之一。尽管如此,Flot.js 也不会因为绘制折线图、饼图、条形图、面积图、甚至堆叠图表而降低其性能。

Flot.js 有一个很完善的文档。当用户遇到困难时,可以很容易地找到解决办法。Flot.js 也支持旧版本的浏览器。

可以选择不使用 npm 来安装 Flot.js,而是在 HTML5 中包含 jQuery 和 JavaScript 文件。

Flot.js 的基本用法代码示例: 


$(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 ]);
});

总结

以上介绍的 JavaScript 库都是高质量的图表库。但是在学习这些库的过程中,可能会因为学习曲线陡峭或是缺乏学习资料而遇到困难,一种很好的方案是将这些库结合起来使用。最后也欢迎大家补充更多的 JavaScript 图表库。

相关推荐:

非常漂亮的免费纯JavaScript图表库

xCharts-基于D3的JavaScript图表库代码详解(图)

ECharts-基于HTML5 Canvas的JavaScript图表库图文详解

以上が9つのJavaScriptチャートライブラリを詳しく解説の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。