svg-chartist
是一个运行于Node.js服务端的Chartist包装器,它基于chartist-svg修改而来。可用于生成静态SVG图表,你可能将所生成的SVG图表插入到HTML页或导出到PDF。
安装
npm install svg-chartist --save
API
svg-chartist
被导出为一个函数,你可以像下面这样引用它:
const chartistSvg = require('svg-chartist');
chartistSvg(type, chartData, opts)
顶层函数,用于生成静态SVG图表。该函数会返回一个Promise,其fulfilled状态会包含所生成静态图表的HTML。
参数
type
{string} 图表类型。可选值有:'bar'
、'line'
、'pie'
chartData
{object} Chartist的数据(data
)选项参数。请参阅:Chartist API[opts]
{object} 可选参数对象[options]
{object} Chartist的options
选项参数。请参阅:Chartist API[resOptions]
{object} Chartist的responsiveOptions
选项参数。请参阅:Chartist API[onDraw]
{Function} Chartist的'draw'
事件临听函数[title]
{object} 图标的标题设置(如:height
、width
、等),标题文本通过 chartData.title
传入[subtitle]
{object} 图标的子标题设置(如:height
、width
、等),子标题文本通过 chartData.title
传入[css]
{string} 自定义的CSS,会追加到Chartist's 的CSS中
返回值
- <Promise> {string} promise,其fulfilled状态会包含所生成静态图表的HTML。
示例
简单的折线图:
const chartistSvg = require('svg-chartist'); const fs = require('fs'); const data = { labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], series: [ [12, 9, 7, 8, 5], [2, 1, 3.5, 7, 3], [1, 3, 4, 5, 6] ] }; const options = { fullWidth: true, chartPadding: { right: 40 } } const opts = { options: options } chartistSvg('line', data, opts).then((html) => { fs.writeFileSync('./examples/simpleLineChart.html', html) })
以上示例,与Chartist官方Simple line chart示例参数一致。
简单的饼状图:
const chartistSvg = require('svg-chartist'); const fs = require('fs'); const data = { series: [5, 3, 4] }; var sum = function(a, b) { return a + b }; const options = { width: 500, height: 300, labelInterpolationFnc: function(value) { return Math.round(value / data.series.reduce(sum) * 100) + '%'; } } const opts = { options: options } chartistSvg('pie', data, opts).then((html) => { fs.writeFileSync('./examples/simplePieChart.html', html) })
以上示例,与Chartist官方Simple pie chart示例参数一致。
自定义柱状图:
const chartistSvg = require('svg-chartist'); const fs = require('fs'); const data = { title: 'Custom bar chart', subtitle: 'by: itbilu.com', labels: ['Q1','Q2','Q3','Q4'], series: [ [80, 50, 100, 75] ] }; const options = { width: 700, height: 350, stackBars: true, axisX: { showLabel: true, showGrid: false, } } const opts = { options: options, title: { height: 50, fill: "#4A5572" }, css: `.ct-series-a .ct-bar, .ct-series-a .ct-line, .ct-series-a .ct-point, .ct-series-a .ct-slice-donut{ stroke: #4A5572 }`, onDraw: function (data) { if(data.type === 'bar') { data.element.attr({ style: 'stroke-width: 30px' }); } } } chartistSvg('bar', data, opts).then((html) => { fs.writeFileSync('./examples/customBarChart.html', html) })