Skip to content

Instantly share code, notes, and snippets.

@mbostock
Forked from mbostock/.block
Last active November 20, 2025 17:35
Show Gist options
  • Select an option

  • Save mbostock/3887235 to your computer and use it in GitHub Desktop.

Select an option

Save mbostock/3887235 to your computer and use it in GitHub Desktop.
Pie Chart
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">
<style>
body {
font: 10px sans-serif;
}
.arc path {
stroke: #fff;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(radius - 70);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.csv("data.csv", function(error, data) {
data.forEach(function(d) {
d.population = +d.population;
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.age); });
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; });
});
</script>
@snehavenky
Copy link

hi,
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 ?
thanks,
Sneha

@mheiber
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 (https://github.com/mbostock/d3/wiki/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 https://github.com/mbostock/d3/wiki/Requests.

@shivambijoria
Copy link

for me:
change: <script src="//d3js.org/d3.v3.min.js"></script>
to

<script src="http://d3js.org/d3.v3.min.js"></script>

@shivambijoria
Copy link

for me
add http:
to script source ,in front of d3js.org/

@dohnuts
Copy link

dohnuts commented Jan 17, 2017

new API update adaptation : https://jsfiddle.net/fhtn5694/1/

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