d3.js: vertical alignment of text in a donut chart

ぃ、小莉子 提交于 2019-12-04 21:56:28

I would put all the legend text elements in a common <g> element which can then be translated to center vertically. Determining actual text sizes in SVG is always a pain, you can look into getBBox() for more information on that. But using a predetermined text height will work fine. Here's a bit of calculation (separated into many steps for clarity):

// hardcoding 36 here, you could use getBBox to get the actual SVG text height using sample text if you really wanted.
var legendItemHeight = 36;

// calculated height of all legend items together
var actualLegendHeight = data.length * legendItemHeight;

// inner diameter
var availableLegendHeight = radius * factor * 2;

// y-coordinate of first legend item (relative to the center b/c the main svg <g> element is translated
var legendOffset = (availableLegendHeight - actualLegendHeight) / 2 - (radius*factor);

And then create a <g> element to hold the <text> elements:

// append all the legend items to a common group which is translated
var l = svg.selectAll('.legend')
    .data(data)
    .enter().append('g')
    .attr('class', 'legend')
    .attr('transform', function(d, i) { 
        return 'translate(0, '+ (legendOffset + i * legendHeight)+')'; 
    });

Modified jsFiddle: http://jsfiddle.net/rshKs/2/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!