Skip to content

Instantly share code, notes, and snippets.

@danharr
Last active August 29, 2015 14:03
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 danharr/0991d6829db40ba040aa to your computer and use it in GitHub Desktop.
Save danharr/0991d6829db40ba040aa to your computer and use it in GitHub Desktop.
Cost of kids

A remake of one of The Guardian's visuals from "Facts are sacred". A bar chart would be far clearer. The paper version was also incorrect and quite misleading

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>add title</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>
#title {
font-family: "helvetica";
font-size: 30px;
color: white;
position: absolute;
left:20px;
top: 20px;
width:300px;
font-weight: bold;
}
.labels, .sum {
font-family: "helvetica";
fill: white;
}
</style>
</head>
<body>
<p id="title">The cost of bringing up a baby</p>
<script type="text/javascript">
var svg = d3.select("body")
.append("svg")
.attr("width", 1000)
.attr("height", 1000);
//alert("g");
var el = d3.select("body").node();
var h = el.clientHeight;
var w= el.clientWidth;
//alert("h is "+h +" w is "+w);
var dataset = [
[0,71780,"Education"],
[71780,62099,"Childcare"],
[133879,18667,"Food"],
[152546,10781,"Clothing"],
[163327,15532,"Holidays"],
[178859,9248,"Hobbies & Toys"],
[188107,7303,"Leisure"],
[195410,4337,"Pocket money"],
[199747,3373,"Furniture"],
[203120,1143,"Personal Care"],
[204263,1143,"Other"]
];
var x = d3.scale.linear().domain([0,d3.sum(dataset,function(d) {return d[1];})]).range([0,w]);
//var y = d3.scale.linear().domain([0,218024]).range([0,w]);
var col = d3.scale.category10();
var viz = svg.append("g");
viz.selectAll(".squares")
.data(dataset)
.enter()
.append("rect")
.attr("class","squares")
.attr("width",function(d) {return x(d[1]);})
.attr("height",h)
.attr("stroke","black")
.style("stroke-width",4)
.attr("x",function(d) {return x(d[0]);})
.attr("y",0)
.style("opacity",1)
.style("fill",function(d,i) {return col(i);});
viz.append("text")
.text("£218,024")
.style("font-size",70)
.attr("x",20)
.attr("y",300)
.attr("class","sum");
viz.selectAll(".labels1")
.data(dataset)
.enter()
.append("text")
.filter(function(d,i) {return d[1] >9000;})
.text(function(d) {return d[2];})
.attr("x",function(d) {return 20+ x(d[0]);})
.attr("y",function(d,i) {return (h*0.4) + (i*110);})
.attr("class","labels labels1")
viz.selectAll(".labels2")
.data(dataset)
.enter()
.append("text")
.filter(function(d,i) {return d[1] >9000;})
.text(function(d) {return "£" + comm(d[1]);})
.attr("x",function(d) {return 20+ x(d[0]);})
.attr("y",function(d,i) {return (h*0.43) + (i*110);})
.attr("class","labels labels1")
.style("font-size",25)
.style("font-weight","bold")
function comm(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment