Skip to content

Instantly share code, notes, and snippets.

Forked from mbostock/.block
Last active November 30, 2017 00:51
  • Star 4 You must be signed in to star a gist
  • Fork 18 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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:

age population
<5 2704659
5-13 4499890
14-17 2159981
18-24 3853788
25-44 14106543
45-64 8819342
≥65 612463
<!DOCTYPE html>
<meta charset="utf-8">
.arc text {
font: 10px sans-serif;
text-anchor: middle;
.arc path {
stroke: #fff;
<svg width="960" height="500"></svg>
<script src=""></script>
var svg ="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()
.value(function(d) { return d.population; });
var path = d3.arc()
.outerRadius(radius - 10)
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")
.attr("class", "arc");
.attr("d", path)
.attr("fill", function(d) { return color(; });
.attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; })
.attr("dy", "0.35em")
.text(function(d) { return; });
Copy link

i'm new to using d3... can you please tell me how to run the above ? i tried using the index.html and csv file ... do i need anything else to run your code ?

Copy link

mheiber commented Apr 23, 2014

Is it a browser security issue? If so, you'll need to do one of two things:

  • Host the directory containing your files. If you have Python installed, then you can navigate to the directory with the files and use python -m SimpleHTTPServer
  • OR store the CSV data as a string and use d3.csv.parse ( You will need to replace the newlines with '\n' because JavaScript won't parse multi-line string literals.

The first option is definitely preferable.

You'll run into the same security issue with other ways of getting data into d3. See

Copy link

for me:
change: <script src="//"></script>

<script src=""></script>

Copy link

for me
add http:
to script source ,in front of

Copy link

dohnuts commented Jan 17, 2017

new API update adaptation :

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment