Skip to content

Instantly share code, notes, and snippets.

@vpj
Forked from mbostock/.block
Last active August 29, 2015 13:57
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 vpj/9636655 to your computer and use it in GitHub Desktop.
Save vpj/9636655 to your computer and use it in GitHub Desktop.
Weya.coffee: Grouped Bar Chart
State Under 5 Years 5 to 13 Years 14 to 17 Years 18 to 24 Years 25 to 44 Years 45 to 64 Years 65 Years and Over
CA 2704659 4499890 2159981 3853788 10604510 8819342 4114496
TX 2027307 3277946 1420518 2454721 7017731 5656528 2472223
NY 1208495 2141490 1058031 1999120 5355235 5120254 2607672
FL 1140516 1938695 925060 1607297 4782119 4746856 3187797
IL 894368 1558919 725973 1311479 3596343 3239173 1575308
PA 737462 1345341 679201 1203944 3157759 3414001 1910571
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar {
fill: steelblue;
}
.x.axis path {
display: none;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="https://rawgithub.com/vpj/weya/master/weya.js"></script>
<script type="text/coffeescript">
margin = {top: 20, right: 20, bottom: 30, left: 40}
width = 960 - margin.left - margin.right
height = 500 - margin.top - margin.bottom
x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1)
x1 = d3.scale.ordinal()
y = d3.scale.linear()
.range([height, 0])
color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"])
svg = null
Weya document.body, ->
@svg
width: width + margin.left + margin.right
height: height + margin.top + margin.bottom, ->
svg = @g transform: "translate(#{margin.left},#{margin.top})"
onLoad = (error, data) ->
ageNames = d3.keys(data[0]).filter((key) -> key isnt "State")
data.forEach (d) ->
d.ages = ageNames.map((name) -> {name: name, value: +d[name]})
x0.domain data.map (d) -> d.State
x1.domain(ageNames).rangeRoundBands [0, x0.rangeBand()]
y.domain [0, d3.max data, ((d) -> d3.max d.ages, ((d) -> d.value))]
Weya svg, ->
for d in data
@g ".g", transform: "translate(#{x0 d.State},0)", ->
for age in d.ages
@rect
width: x1.rangeBand()
x: x1 age.name
y: y age.value
height: height - y age.value
fill: color age.name
for d, i in ageNames.slice().reverse()
@g ".legend", transform: "translate(0,#{i * 20})", ->
@rect x: width - 18, width: 18, height: 18, fill: color d
@text
x: width - 24, y: 9, dy: ".35em"
style: {'text-anchor': "end"}, d
d3.csv "data.csv", onLoad
</script>
<script type="text/javascript" src="http://rawgithub.com/jashkenas/coffee-script/master/extras/coffee-script.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment