Skip to content

Instantly share code, notes, and snippets.

@widged
Forked from mbostock/.block
Last active December 15, 2015 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save widged/5235493 to your computer and use it in GitHub Desktop.
Save widged/5235493 to your computer and use it in GitHub Desktop.

Negative Bar graph transposed from horizontal to vertical

<!DOCTYPE html>
<meta charset="utf-8">
<title>Bar Chart with Negative Values</title>
<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="http://d3js.org/d3.v3.min.js"></script>
<script>
var data = [-15, -20, -22, -18, 2, 6, -26, -18];
var margin = {top: 30, right: 30, bottom: 30, left: 30},
width = 960 - margin.left - margin.right,
height = 800 - margin.top - margin.bottom;
var y0 = Math.max(-d3.min(data), d3.max(data));
var x = d3.scale.ordinal()
.domain(d3.range(data.length))
.rangeRoundBands([0, width], .2);
var y = d3.scale.linear()
.domain([y0, -y0])
.range([0, height])
.nice();
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
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 + ")");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", function(d) { return d < 0 ? "bar negative" : "bar positive"; })
.attr("y", function(d) { return y(Math.max(0, d)); })
.attr("x", function(d, i) { return x(i); })
.attr("height", function(d) { return Math.abs(y(d) - y(0)); })
.attr("width", x.rangeBand());
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "x axis")
.append("line")
.attr("x1", 0)
.attr("x2", width)
.attr("y1", y(0))
.attr("y2", y(0));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment