Skip to content

Instantly share code, notes, and snippets.

@interwebjill
Last active March 11, 2018 19:44
Show Gist options
  • Save interwebjill/2c87d633a0c1032e41be5d693b898b27 to your computer and use it in GitHub Desktop.
Save interwebjill/2c87d633a0c1032e41be5d693b898b27 to your computer and use it in GitHub Desktop.
Line bar chart generator
license: mit
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment