Skip to content

Instantly share code, notes, and snippets.

@jiankuang
Last active May 29, 2016 17:04
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 jiankuang/a591ff3331044f8c9a59764a1424bb07 to your computer and use it in GitHub Desktop.
Save jiankuang/a591ff3331044f8c9a59764a1424bb07 to your computer and use it in GitHub Desktop.
D3 Layout Pie Chart
<body>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript">
var data = [10, 50, 80];
var r = 300; // outer radius
var color = d3.scale.ordinal()
.range(["red", "blue", "orange"]);
var svg = d3.select("body").append("svg")
.attr("width", 700)
.attr("height", 700);
var group = svg.append("g")
.attr("transform", "translate(300, 300)"); // set center of pie to 300,300
var arc = d3.svg.arc()
.innerRadius(150)
.outerRadius(r);
var pie = d3.layout.pie()
.value(function(d) { return d; }); // pie function transform data into specific format
var arcs = group.selectAll(".arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "arc");
arcs.append("path")
.attr("d", arc) // here the arc function works on every record d of data
.attr("fill", function(d){ return color(d.data); });
arcs.append("text")
.attr("transform", function(d){ return "translate(" + arc.centroid(d) + ")"; }) // put text at the center of every arc
.attr("text-anchor", "middle")
.attr("font-size", "1.5em")
.text(function(d) { return d.data; });
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment