Skip to content

Instantly share code, notes, and snippets.

@mbostock
Created February 18, 2016 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mbostock/79a82f4b9bffb69d89ae to your computer and use it in GitHub Desktop.
Save mbostock/79a82f4b9bffb69d89ae to your computer and use it in GitHub Desktop.
Bar Chart with Negative Values II
license: gpl-3.0
name value
A -15
B -20
C -22
D -18
E 2
F 6
G 26
H 18
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.bar--positive {
fill: steelblue;
}
.bar--negative {
fill: brown;
}
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 20, right: 30, bottom: 40, left: 30},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.ordinal()
.rangeRoundBands([0, height], 0.1);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickSize(6, 0);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.tsv("data.tsv", type, function(error, data) {
x.domain(d3.extent(data, function(d) { return d.value; })).nice();
y.domain(data.map(function(d) { return d.name; }));
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", function(d) { return "bar bar--" + (d.value < 0 ? "negative" : "positive"); })
.attr("x", function(d) { return x(Math.min(0, d.value)); })
.attr("y", function(d) { return y(d.name); })
.attr("width", function(d) { return Math.abs(x(d.value) - x(0)); })
.attr("height", y.rangeBand());
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
var tickNegative = svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + x(0) + ",0)")
.call(yAxis)
.selectAll(".tick")
.filter(function(d, i) { return data[i].value < 0; });
tickNegative.select("line")
.attr("x2", 6);
tickNegative.select("text")
.attr("x", 9)
.style("text-anchor", "start");
});
function type(d) {
d.value = +d.value;
return d;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment