Skip to content

Instantly share code, notes, and snippets.

@gustavderdrache
Created July 5, 2013 20:09
Show Gist options
  • Save gustavderdrache/5936923 to your computer and use it in GitHub Desktop.
Save gustavderdrache/5936923 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
body {
width: 960px;
margin: auto;
}
div {
width: 470px;
margin: 5px 0;
}
#hi {
float: right;
}
#lo {
float: left;
}
</style>
</head>
<body style="width: 960px; margin: auto">
<h1>descriptive chart title</h1>
<div id="hi"><p>high-performers</p></div>
<div id="lo"><p>low-performers</p></div>
<script>
var pad = {
left: 0,
right: 60,
top: 10,
bottom: 10
};
var data = {
lo: [
{ race: 'White', v: 31 },
{ race: 'Black', v: 28 },
{ race: 'Hispanic', v: 34 },
{ race: 'Asian', v: 2 },
{ race: 'Asian/Pacific Islander', v: 0 },
{ race: 'Two or more races', v: 2 }
],
hi: [
{ race: 'White', v: 72 },
{ race: 'Black', v: 5 },
{ race: 'Hispanic', v: 10 },
{ race: 'Asian', v: 10 },
{ race: 'Asian/Pacific Islander', v: 0 },
{ race: 'Two or more races', v: 3 }
]
};
var height = 500 - pad.top - pad.bottom;
var width = 470 - pad.left - pad.right;
var x = d3.scale.linear()
.domain([0, 100])
.range([0, width]);
var y = d3.scale.ordinal()
.domain([0, 1, 2, 3, 4, 5, 6])
.rangeBands([0, height], 0.1);
var colors = [ '#f3b602', '#0bcca6', '#248ff9', '#80ce36', '#bf1ee0', '#fc6c00' ];
['hi', 'lo'].forEach(function (which) {
var svg = d3.select('#' + which)
.append('svg')
.attr('height', 500)
.attr('width', 470);
var chart = svg.append('g')
.attr('transform', 'translate(' + pad.left + ', ' + pad.top + ')');
chart.selectAll('rect')
.data(data[which])
.enter()
.append('rect')
.attr('x', 0)
.attr('y', function (d, i) { return y(i); })
.attr('height', y.rangeBand())
.attr('width', function (d) { return x(d.v); })
.attr('fill', function (d, i) { return colors[i]; });
var text = chart.selectAll('text')
.data(data[which])
.enter()
.append('text')
.attr('x', function (d) { return x(d.v) + 5; })
.attr('font-family', 'sans-serif');
text.insert('tspan')
.attr('y', function (d, i) { return y(i) + y.rangeBand()/2; })
.attr('font-weight', 'bold')
.attr('font-size', '24px')
.text(function (d) { return d.v + '%'; });
text.insert('tspan')
.attr('x', function (d) { return x(d.v) + 5; })
.attr('y', function (d, i) { return y(i) + y.rangeBand()/2 + 15; })
.attr('font-size', '12px')
.text(function (d) { return d.race; });
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment