In response to: http://stackoverflow.com/questions/27042222/create-custom-a-d3-generator
forked from jsl6906's block: Line bar chart generator
license: mit |
In response to: http://stackoverflow.com/questions/27042222/create-custom-a-d3-generator
forked from jsl6906's block: Line bar chart generator
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<body> | |
<script src="http://d3js.org/d3.v4.min.js"></script> | |
<script> | |
height = 500; | |
d3.functor = function functor(v) { | |
return typeof v === "function" ? v : function() { | |
return v; | |
}; | |
}; | |
function lineBarGenerator() { | |
//set defaults | |
var x1 = function(d) { return d.x; }, | |
y1 = height, | |
y2 = function(d) { return -d.y; }; | |
//returned function to generate lineBar path | |
function lineBar(d) { | |
var line_x1 = d3.functor(x1).call(this, d), | |
line_y2 = d3.functor(y2).call(this, d); | |
return `M ${line_x1}, ${y1} v ${-line_y2}`; | |
} | |
//getter-setter methods | |
lineBar.x1 = function(value) { | |
if (!arguments.length) return x1; x1 = value; return lineBar; | |
}; | |
lineBar.y1 = function(value) { | |
if (!arguments.length) return y1; y1 = value; return lineBar; | |
}; | |
lineBar.y2 = function(value) { | |
if (!arguments.length) return y2; y2 = value; return lineBar; | |
}; | |
return lineBar; | |
} | |
var svg = d3.select("body").append("svg") | |
.attr("width", "500px") | |
.attr("height", "500px"); | |
var lineBar = lineBarGenerator() | |
.x1(function(d) { return d.x1; }) | |
.y2(function(d) { return d.y2; }); | |
var data = [ | |
{x1: 150, y2: 100, stroke: "green"}, | |
{x1: 200, y2: 150, stroke: "red"}, | |
{x1: 100, y2: 250, stroke: "blue"} | |
]; | |
svg.selectAll("path.lineBar") | |
.data(data) | |
.enter().append("path") | |
.attr("class", "lineBar") | |
.attr("d", lineBar) | |
.style("stroke", function(d) { return d.stroke; }); | |
</script> |