javascript - Adding Legend on a basic chart -


i brand new d3.js , stackoverflow please pardon if ask basic. have basic donut chart modification of normal donut chart since can see there 1 on top of another. wondering if possible add label right on chart. able add legend , label outside chart want able add label right on chart itself.

this code chart

var dataset = {   data1: [53245, 28479, 19697, 24037, 40245],   data2: [53245, 28479, 19697, 24037, 40245] };  var width = 460,     height = 300,     cwidth = 45;  var color = d3.scale.category20();  var pie = d3.layout.pie()     .sort(null);  var arc = d3.svg.arc();  var svg = d3.select("body").append("svg")     .attr("width", width)     .attr("height", height)     .append("g")     .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");  var gs = svg.selectall("g").data(d3.values(dataset)).enter().append("g"); var path = gs.selectall("path")     .data(function(d) { return pie(d); })   .enter().append("path")     .attr("fill", function(d, i) { return color(i); })     .attr("d", function(d, i, j) { return arc.innerradius(10+cwidth*j).outerradius(cwidth*(j+1))(d); }); 

this fiddle. highly pleased suggestions able add label , legend. want label on top of both charts in fiddle.

is you're looking for? fiddle.

essentially append text element positioned using angle of path element.

var angle = d.endangle - d.startangle; var loc = d.startangle - (math.pi/2) + (angle/2); return math.sin(loc) * radius; 

if want labels on left side not overlap onto chart use similar following

var textlength = []; genter.selectall("text").each(function () {     textlength.push(this.getcomputedtextlength()); }); 

to lengths of text objects, can modify either .attr("x", ...) or .attr("transform", "translate(x,0)") when d.startangle greater pi (meaning on left side of chart), subtracting text length x element position further left.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -