D3.js donut chart with labels
HTML
<script src="http://d3js.org/d3.v3.min.js"></script>
<div id="chart"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
CSS
#chart {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
width: 960px;
height: 500px;
position: relative;
}
svg {
width: 100%;
height: 100%;
}
path.slice{
stroke-width:2px;
}
polyline{
opacity: .3;
stroke: black;
stroke-width: 2px;
fill: none;
}
.labelValue
{
font-size: 60%;
opacity: .5;
}
.toolTip {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
position: absolute;
display: none;
width: auto;
height: auto;
background: none repeat scroll 0 0 white;
border: 0 none;
border-radius: 8px 8px 8px 8px;
box-shadow: -3px 3px 15px #888888;
color: black;
font: 12px sans-serif;
padding: 5px;
text-align: center;
}
text {
font: 12px sans-serif;
}
</style>
JavaScript
d3.select("input[value=\"total\"]").property("checked", true);
var svg = d3.select("#chart")
.append("svg")
.append("g")
svg.append("g")
.attr("class", "slices");
svg.append("g")
.attr("class", "labelName");
svg.append("g")
.attr("class", "labelValue");
svg.append("g")
.attr("class", "lines");
var width = 960,
height = 450,
radius = Math.min(width, height) / 2;
var pie = d3.layout.pie()
.sort(null)
.value(function(d) {
return d.value;
});
var arc = d3.svg.arc()
.outerRadius(radius * 0.8)
.innerRadius(radius * 0.4);
var outerArc = d3.svg.arc()
.innerRadius(radius * 0.9)
.outerRadius(radius * 0.9);
var legendRectSize = (radius * 0.05);
var legendSpacing = radius * 0.02;
var div = d3.select("#chart").append("div").attr("class", "toolTip");
svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var colorRange = d3.scale.category20();
var color = d3.scale.ordinal()
.range(colorRange.range());
datasetTotal = [
{label:"Category 1", value:19},
{label:"Category 2", value:5},
{label:"Category 3", value:13},
{label:"Category 4", value:17},
{label:"Category 5", value:19},
{label:"Category 6", value:27}
];
change(datasetTotal);
d3.selectAll("input")
.on("change", selectDataset);
function selectDataset()
{
var value = this.value;
if (value == "total")
{
change(datasetTotal);
}
else if (value == "option1")
{
change(datasetOption1);
}
else if (value == "option2")
{
change(datasetOption2);
}
}
function change(data) {
/* ------- PIE SLICES -------*/
var slice = svg.select(".slices").selectAll("path.slice")
.data(pie(data), function(d){ return d.data.label });
slice.enter()
.insert("path")
.style("fill", function(d) { return color(d.data.label); })
.attr("class", "slice");
/*slice
.transition().duration(1000)
.attrTween("d", function(d) {
this._current = this._current || d;
...