Skip to content

Instantly share code, notes, and snippets.

@erikhazzard
Created May 19, 2013 19:00
Show Gist options
  • Save erikhazzard/5608603 to your computer and use it in GitHub Desktop.
Save erikhazzard/5608603 to your computer and use it in GitHub Desktop.
negative bar chart
{"description":"negative bar chart","endpoint":"","display":"svg","public":true,"require":[],"fileconfigs":{"inlet.js":{"default":true,"vim":false,"emacs":false,"fontSize":12},"style.css":{"default":true,"vim":false,"emacs":false,"fontSize":12}},"fullscreen":false,"play":false,"loop":false,"restart":false,"autoinit":true,"pause":true,"loop_type":"period","bv":false,"nclones":15,"clone_opacity":0.4,"duration":3000,"ease":"linear","dt":0.01}
var data = [
{"name": "A", "value": -15},
{"name": "B", "value": -20},
{"name": "C", "value": -22},
{"name": "D", "value": -18},
{"name": "E", "value": 2},
{"name": "F", "value": 6},
{"name": "G", "value": -26},
{"name": "H", "value": -1}
];
var margin = {top: 30, right: 30, bottom: 10, left: 30},
width = 560 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var y = d3.scale.linear()
.range([0, height]);
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.2);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var svg = d3.select("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
y.domain(d3.extent(data, function(d) { return +d.value; })).nice();
x.domain(data.map(function(d) { return d.name; }));
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", function(d) { return d.value < 0 ? "bar negative" : "bar positive"; })
.attr("x", function(d) { return x(d.name); })
.attr("y", function(d) { return y(Math.min(0, d.value)); })
.attr("width", function(d) { return x.rangeBand(); })
.attr("height", function(d,i){ return Math.abs(y(d.value) - y(0)); });
svg.append("g")
.attr("class", "x axis")
.call(yAxis);
svg.append("g")
.attr("class", "y axis")
.append("line")
.attr("y1", y(0))
.attr("y2", y(0))
.attr("x2", width);
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
.lineWrapper .line {
fill: none;
stroke: #a0a0a0;
stroke: none;
stroke-width: 2px;
}
.quintileTotalWrapper .positive {
fill: #cceeea;
stroke: #7cd4c8;
}
.quintileTotalWrapper .negative {
fill: #eebfa5;
stroke: #e27335;
}
.quintileTotalWrapper {
fill: #cceeea;
stroke: #7cd4c8;
stroke-width: 2px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment