Skip to content

Instantly share code, notes, and snippets.

@campreb
Last active December 18, 2015 01:38
Show Gist options
  • Save campreb/5704734 to your computer and use it in GitHub Desktop.
Save campreb/5704734 to your computer and use it in GitHub Desktop.
D3 Ethnic Groups Demo
var groups = [
{name:"European",value:2949.0 },
{name:"Asian",value:924.0 },
{name:"Pacific",value:99.0 },
{name:"M\u0101ori",value:255.0 },
{name:"MELAA",value:87.0 },
{name:"Other",value:360.0}
];
var table = d3.select("#ethnic-group-data");
var headers = table.selectAll("thead th");
var width = 400,
height = 300,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal().domain([0,1,2,3,4])
.range(["#AA0044","#0CCDF6","#B7A712","#9A3CF3","#0C6477","#4347C0"]);
var arc = d3.svg.arc()
.outerRadius(radius - 30)
.innerRadius(radius - 90);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.value; });
var svg = d3.select("#paper").append("svg")
.attr("width", width)
.attr("height", height)
.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var get_value = function(group){
return group.value;
};
var population = d3.sum(groups, get_value);
var max = d3.max(groups, get_value);
var min = d3.min(groups, get_value);
var percentify = d3.format(".1%");
var fontsize = d3.scale.linear().domain([min,max]).range([16,36]) ;
var show_number = function(value){
svg.append("text")
.attr("class", "percentage")
.text(percentify(value/population))
.attr("x", 0)
.attr("y", 0)
.style("font-size", fontsize(value))
};
var hide_number = function(){
svg.selectAll(".percentage").remove();
};
var g = svg.selectAll(".arc")
.data(pie(groups))
.enter().append("g")
.attr("class","arc")
.on("mouseover",function(d,i){
d3.select(this)
.style("stroke","#fff")
.style("stroke-width","3px");
show_number(d.value);
}).on("mouseout", function(){
d3.select(this).style("stroke",null);
hide_number();
});
g.append("path")
.attr("d", arc)
.style("fill", function(d,i) { return color(i); });
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
body{
font-family: Helvetica, sans;
}
#paper{
width:400px;
height:300px;
}
text.percentage{
text-anchor: middle;
alignment-baseline: middle;
font-weight: bold;
fill: #999;
}
</style>
</head>
<body>
<table id='ethnic-group-data'>
<thead>
<tr>
<th>Name</th>
<th>2006</th>
</tr>
</thead>
<tbody>
<tr>
<td>European</td>
<td>2949</td>
</tr>
<tr>
<td>Asian</td>
<td>924</td>
</tr>
<tr>
<td>Pacific</td>
<td>99</td>
</tr>
<tr>
<td>M&#257;ori</td>
<td>255</td>
</tr>
<tr>
<td>MELAA</td>
<td>87</td>
</tr>
<tr>
<td>Other</td>
<td>360</td>
</tr>
</tbody>
</table>
<div id="paper"></div>
<script type="text/javascript" src='//cdnjs.cloudflare.com/ajax/libs/d3/3.1.6/d3.min.js'></script>
<script type="text/javascript" src='application.js'></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment