Skip to content

Instantly share code, notes, and snippets.

@reconbot
Forked from mbostock/.block
Last active November 30, 2017 00:53
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 reconbot/6ea75f2769fd0436709210842a161831 to your computer and use it in GitHub Desktop.
Save reconbot/6ea75f2769fd0436709210842a161831 to your computer and use it in GitHub Desktop.
Pie Chart
license: gpl-3.0

This pie chart is constructed from a CSV file storing the populations of various age groups. The chart employs a number of D3 features:

object size
Tag 23008166
ListiclePost 287556055
Image 567028097
Path 211299017
PageClip 2064261
PostRevision 2628046948
ArticlePost 2351865643
PostClip 54057022
PostsByAuthorsFeed 7471678
Notification 849750
ContentAlert 45878490
FeedZone 7465694
SlideshowPost 53069205
ProfilePage 5103924
TriviaPost 2089912
User 4999785
PostsByTagsFeed 35980
WatsonCategory 296007
VideoPost 5979584
OembedClip 8015
FlowchartPost 93834
IabCategory 97075
ComicPost 154226
NotificationSegment 14509
FeaturePost 2936267
Oembed 29348
TopicPage 30270
AdClip 2560
ListZone 4754
Site 1701
FeatureZone 5304
MenuZone 1074
RelatedPostsFeed 171
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.arc text {
font: 10px sans-serif;
text-anchor: middle;
}
.arc path {
stroke: #fff;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
radius = Math.min(width, height) / 2,
g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var color = d3.scaleOrdinal(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var pie = d3.pie()
.sort(null)
.value(function(d) { return d.population; });
var path = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var label = d3.arc()
.outerRadius(radius - 40)
.innerRadius(radius - 40);
d3.csv("data.csv", function(d) {
d.population = +d.population;
return d;
}, function(error, data) {
if (error) throw error;
var arc = g.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
arc.append("path")
.attr("d", path)
.attr("fill", function(d) { return color(d.data.age); });
arc.append("text")
.attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; })
.attr("dy", "0.35em")
.text(function(d) { return d.data.age; });
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment