Responsive D3 Pie Chart with D3.legend.js
HTML
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://www.rationalplayground.com/js/d3/d3.legend.js"></script>
<div id="ChartAccessAgesByCountD3" style="height:260px;" data-drilldown-destination="filelist_by_category" data-drilldown-key="atime" ></div>
CSS
.legend rect {
fill:white;
opacity:0.4;
}
#ChartAccessAgesByCountD3 svg {
height:500px;
padding-top:50px;
}
.legend-items text {
cursor: default;
}
JavaScript
var st = {};
st.data = [{
"label": "less than a week",
"value": 169,
"pos": 0
}, {
"label": "1 week - 30 days",
"value": 1,
"pos": 1
}, {
"label": "30 - 90 days",
"value": 22,
"pos": 2
}, {
"label": "90 - 180 days",
"value": 35,
"pos": 3
}, {
"label": "180 days - 1 year",
"value": 47,
"pos": 4
}, {
"label": "more than 1 year",
"value": 783,
"pos": 5
},
{
"label": "more than 1 year",
"value": 783,
"pos": 5
}];
drawD3PieChart("#ChartAccessAgesByCountD3", st.data);
function drawD3PieChart(sel, data) {
// clear any previously rendered svg
$(sel + " svg").remove();
// compute total
tot = 0;
data.forEach(function(e){ tot += e.value; });
var w = $(sel).width();
var h = $(sel).height();
var r = Math.min(w, h) /2;
var color = d3.scale.category20c();
var vis = d3.select(sel).append("svg:svg").attr("data-chart-context",sel).data([data]).attr("width", w).attr("height", h).append("svg:g").attr("transform", "translate(" + (w / 2) + "," + r + ")");
var svgParent = d3.select("svg[data-chart-context='" + sel + "']");
var pie = d3.layout.pie().value(function(d){return d.value;});
var arc = d3.svg.arc().outerRadius(r);
var arcs = vis.selectAll("g.slice").data(pie).enter().append("svg:g").attr("class","slice");
arcs.append("svg:path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("stroke", "#fff")
.attr("stroke-width", "0")
.attr("d", function(d) {
return arc(d);
})
.attr("data-legend",function(d) { return d.data.label; })
.attr("data-legend-pos",function(d) { return d.data.pos; })
.classed("slice",true)
.attr("style","cursor:pointer;")
.append("svg:title")
.text(function(d) { return d.data.label; });
arcs.append("svg:text").attr("transform", function(d){
d.innerRadius = 0;
d.outerRadius = r;
return "translate(" + arc.centroid(d) + ")";}).attr("text-anchor", "middle").text( function(d, i) {
return (data[i].value / tot ) *...