简体   繁体   中英

D3 - legend won't visualize

I've tried to create a legend using inspiration from http://zeroviscosity.com/d3-js-step-by-step/step-3-adding-a-legend . However, despite having almost the exact same code, the legend isn't visualized. Here's the jsfiddle and the code: http://jsfiddle.net/u5hd25qs/

var width = $(window).width();
var height = $(window).height() / 2;


var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var legendRectSize = 36; // 18
var legendSpacing = 8; // 4
var recordTypes = []

recordTypes.push({
    text : "call",
    color : "#438DCA"
});

recordTypes.push({
    text : "text",
    color : "#70C05A"
});

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

legend.append('rect')
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.style('fill', function (d) {
    return d.color
})
.style('stroke', function (d) {
    return d.color
});

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

Your code works okay, but this is what you generate:

<g class="legend" transform="translate(-72,-44)">...

Because your translate rule has negative values in it, the legend is positioned outside the screen (it is simply not visible).

Now, the example you're basing your work on has a pie chart that has already been translate d to the center of the screen, so negative values are not an issue.

You need to change your math or wrap the legend in some container which you can position in the same way as the pie chart example:

legendContainer
  .attr('transform', 'translate(' + (width / 2) +  ',' + (height / 2) + ')');

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