Skip to content

Instantly share code, notes, and snippets.

@santiaago
Created December 11, 2014 00:09
Show Gist options
  • Save santiaago/8ece9bd7245def76972d to your computer and use it in GitHub Desktop.
Save santiaago/8ece9bd7245def76972d to your computer and use it in GitHub Desktop.
bar chart
<!DOCTYPE html>
<meta charset="utf-8">
<title>Bar Chart with Negative Values</title>
<style>
.bar.positive {
fill: #B9E397;
}
.bar.negative {
fill: #D46A6A;
}
.bar.neutral {
fill: #7282AA;
}
.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 margin = {top: 30, right: 10, bottom: 10, left: 10},
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], .2);
var xAxis = d3.svg.axis()
.scale(x)
.orient("top");
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("barChartData.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) {
if (d.value < 0){
return "bar negative";
} else {
console.log(d.name);
if(d.name == 'neutral'){
return "bar neutral";
}
return "bar 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")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.append("line")
.attr("x1", x(0))
.attr("x2", x(0))
.attr("y2", height);
});
function type(d) {
d.value = +d.value;
return d;
}
</script>
name value
positive 50
negative -30
neutral 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment