简体   繁体   中英

d3.js donut chart with legend outside donut

In the following code, I would like to put the donut legends outside the donut, on its right:

http://bl.ocks.org/juan-cb/1984c7f2b446fffeedde

Which line code should I change to do it?

   var legend = svg.selectAll('.legend')
    .data(color.domain())
    .enter()
    .append('g')
    .attr('class', 'legend')
    .attr('transform', function(d, i) {
        var height = legendRectSize + legendSpacing;
        var offset =  height * color.domain().length / 2;
        var horz = -3 * legendRectSize;
        var vert = i * height - offset;
        return 'translate(' + horz + ',' + vert + ')';
    });

legend.append('rect')
    .attr('width', legendRectSize)
    .attr('height', legendRectSize)
    .style('fill', color)
    .style('stroke', color);

legend.append('text')
    .attr('x', legendRectSize + legendSpacing)
    .attr('y', legendRectSize - legendSpacing)
    .text(function(d) { return d; });

Something similar to this one:

http://www.jqueryscript.net/demo/jQuery-Plugin-To-Convert-Tabular-Data-Into-Donut-Charts-Chart-js/

Edit: the solution was just a matter of changing horizontal and vertical coordinates. No need of complicated stuff.

These 2 variables:

var horz = -3 * legendRectSize; // X-axis translation.
var vert = i * height - offset; // Y-axis translation.

You could modify horz and vert formulas for translating. Like this:

var horz = 30 * legendRectSize; // Will be right side of the donut chart.
var vert = i * height - offset; // Still at the middle of the donut chart vertically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM