Last active
July 5, 2018 05:50
-
-
Save Orbifold/d6dbc1ef67e963caad86d25d449689cb to your computer and use it in GitHub Desktop.
Creating a pie-chart with NodeJS and d3.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
var path = require('path'); | |
var d3 = require('d3'); | |
const jsdom = require("jsdom"); | |
const JSDOM = jsdom.JSDOM; | |
var chartWidth = 500, chartHeight = 500; | |
var arc = d3.svg.arc() | |
.outerRadius(chartWidth / 2 - 10) | |
.innerRadius(0); | |
var colours = ['#F00', '#000', '#000', '#000', '#000', '#000', '#000', '#000', '#000']; | |
function go(pieData, outputLocation) { | |
if(!pieData) pieData = [12, 31]; | |
if(!outputLocation) outputLocation = path.join(__dirname, './test.svg'); | |
const dom = new JSDOM(""); | |
dom.window.d3 = d3.select(dom.window.document); //get d3 into the dom | |
//do yr normal d3 stuff | |
var svg = dom.window.d3.select('body') | |
.append('div').attr('class', 'container') //make a container div to ease the saving process | |
.append('svg') | |
.attr({ | |
xmlns: 'http://www.w3.org/2000/svg', | |
width: chartWidth, | |
height: chartHeight | |
}) | |
.append('g') | |
.attr('transform', 'translate(' + chartWidth / 2 + ',' + chartWidth / 2 + ')'); | |
svg.selectAll('.arc') | |
.data(d3.layout.pie()(pieData)) | |
.enter() | |
.append('path') | |
.attr({ | |
'class': 'arc', | |
'd': arc, | |
'fill': function(d, i) { | |
return colours[i]; | |
}, | |
'stroke': '#fff' | |
}); | |
fs.writeFileSync(outputLocation, dom.window.d3.select('.container').html()) //using sync to keep the code simple | |
} | |
go() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "node-d3", | |
"version": "1.0.0", | |
"description": "Serverside SVG via D3 & jsdom", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "[email protected]", | |
"license": "AGPLv3", | |
"dependencies": { | |
"d3": "3.5.5", | |
"jsdom": "*" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for d3js v5