A variation of the bar chart with negative values example using a custom axis to flip the tick orientation for the negative bars.
forked from mbostock's block: Bar Chart with Negative Values II
xxxxxxxxxx
<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 = 1900 - 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.csv("marginsfl.csv", type, function(error, data) {
x.domain(d3.extent(data, function(d) { return d.marginClinton; })).nice();
y.domain(data.map(function(d) { return d.district; }));
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", function(d) { return "bar bar--" + (d.marginClinton < 0 ? "negative" : "positive"); })
.attr("x", function(d) { return x(Math.min(0, d.marginClinton)); })
.attr("y", function(d) { return y(d.district); })
.attr("width", function(d) { return Math.abs(x(d.marginClinton) - 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].marginClinton < 0; });
tickNegative.select("line")
.attr("x2", 6);
tickNegative.select("text")
.attr("x", 9)
.style("text-anchor", "start");
});
function type(d) {
d.marginClinton = +d.marginClinton;
return d;
}
</script>
https://d3js.org/d3.v3.min.js