Reputation: 741
Is it possible to create charts, e.g. bars and pies with custom icons using NodeJS?
Upvotes: 43
Views: 109894
Reputation: 600
For my purposes, I wanted to just plot a chart without spinning up a localhost server or anything. So I used chartjs-node-canvas
and chart.js
Install with:
npm i chartjs-node-canvas chart.js
In this I write it to a file to show it worked but I personally just needed the Base64 string to upload somewhere
// Install libs with: npm i chartjs-node-canvas chart.js
// Docs https://www.npmjs.com/package/chartjs-node-canvas
// Config documentation https://www.chartjs.org/docs/latest/axes/
const fs = require('fs');
const { ChartJSNodeCanvas } = require('chartjs-node-canvas');
const width = 400; //px
const height = 400; //px
const backgroundColour = 'white'; // Uses https://www.w3schools.com/tags/canvas_fillstyle.asp
const chartJSNodeCanvas = new ChartJSNodeCanvas({ width, height, backgroundColour });
const configuration = {
type: 'line', // for line chart
data: {
labels: [2018, 2019, 2020, 2021],
datasets: [{
label: "Sample 1",
data: [10, 15, -20, 15],
fill: false,
borderColor: ['rgb(51, 204, 204)'],
borderWidth: 1,
xAxisID: 'xAxis1' //define top or bottom axis ,modifies on scale
},
{
label: "Sample 2",
data: [10, 30, 20, 10],
fill: false,
borderColor: ['rgb(255, 102, 255)'],
borderWidth: 1,
xAxisID: 'xAxis1'
},
],
},
options: {
scales: {
y: {
suggestedMin: 0,
}
}
}
}
async function run() {
const dataUrl = await chartJSNodeCanvas.renderToDataURL(configuration);
const base64Image = dataUrl
var base64Data = base64Image.replace(/^data:image\/png;base64,/, "");
fs.writeFile("out.png", base64Data, 'base64', function (err) {
if (err) {
console.log(err);
}
});
return dataUrl
}
run()
Here's the docs https://www.npmjs.com/package/chartjs-node-canvas and the Config documentation is here https://www.chartjs.org/docs/latest/axes/
Upvotes: 7
Reputation: 145152
d3 is probably your best bet. It can generate nearly any type of chart imaginable.
You can generate the charts directly in the browser, or if you really need an image file, you can use the module in node and convert the output to an image.
Upvotes: 23
Reputation: 524
You can use any charts library, basically. For example:
On your server template code, you might want to output the data using server variable. Example below using swig template engine, ExpressJS and Chartist library
<div class="ct-chart ct-perfect-fourth"></div>
<script>
new Chartist.Line('.ct-chart', {
labels: {{ chartLabel | raw }},
series : [{{ charts | raw}}]
}, {
axisY: {
onlyInteger: true
}
});
</script>
Find out more about other charts library here
Upvotes: 10
Reputation: 1108
using highcharts
you have to install
npm install -g node-highcharts
refer the following link
https://github.com/davidpadbury/node-highcharts
Upvotes: 1