Skip to content

Instantly share code, notes, and snippets.

@boertel
Created June 25, 2013 23:01
Show Gist options
  • Save boertel/5863227 to your computer and use it in GitHub Desktop.
Save boertel/5863227 to your computer and use it in GitHub Desktop.
Spend
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="//punchtab.github.io/Punchdation/static/css/punchdation/fonts.css" />
<style>
body {
font-family: "Bariol";
}
text {
fill: #fff;
}
.members {
fill: #3C83B8 !important;
}
.anonymous {
fill: #00B06D !important;
}
text.title {
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript">
var margin = {top: 20, right: 20, bottom: 20, left: 20},
width = 560 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
function random() {
return Math.random() * 100;
}
var dataset = {
members: random(),
anonymous: random()
};
/*
Build data to be format like following:
[
{key: "members", x0: 0, x: 100},
{key: "anonymous", x0: 100, x: 50},
]
*/
var x0 = 0;
var data = d3.keys(dataset).map(function (key) {
var serie = {
key: key,
x0: x0,
x: dataset[key]
};
x0 += dataset[key];
return serie;
});
var x = d3.scale.linear()
.domain([0, (data[data.length - 1].x0 + data[data.length - 1].x)])
.rangeRound([0, width]) // results of calling the function x are rounded
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 + ")");
var bar = svg.selectAll("g.bar")
.data(data)
.enter()
.append("g")
.attr("class", function (d) { return "bar " + d.key; })
bar.append("rect")
.attr("x", function (d) { return x(d.x0); })
.attr("width", function (d) { return x(d.x); })
.attr("y", 0)
.attr("height", 40)
var label = svg.selectAll("g.label")
.data(data)
.enter()
.append("g")
.attr("class", function (d) { return "label " + d.key; })
label.append("text")
.attr("class", "value")
.attr("y", 27)
// !i for readability so the order is preserved (handle only 2 values)
.attr("x", function (d, i) { return !i ? x(d.x0) : x(d.x0) + x(d.x) ; })
.attr("dx", function (d, i) { return !i ? 10 : -10; })
.style("text-anchor", function (d, i) { return !i ? "start" : "end"; })
.text(function (d) { return "$" + d.x.toFixed(2); })
label.append("text")
.attr("class", function (d) { return "title " + d.key; })
.attr("y", 57)
.attr("x", function (d, i) { return !i ? x(d.x0) : x(d.x0) + x(d.x) ; })
.attr("dx", function (d, i) { return !i ? 10 : -10; })
.style("text-anchor", function (d, i) { return !i ? "start" : "end"; })
.text(function (d) { return d.key; })
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment