如何向多行系列图表添加图例?我试过,但没有任何传说显示.
这里的区块:
当各种系列收敛到同一点时,有一个缺陷,如零.所有的标签将被叠加在一起.一个传统的传说,而不是去使用这些标签.
我试过添加这个
- var legend = svg.append("g")
- .attr("class","legend")
- .attr("height",100)
- .attr("width",100)
- .attr('transform','translate(-20,50)');
- legend.selectAll('rect')
- .datum(function(d) { return {name: d.name,value: d.values[d.values.length - 1]}; })
- .append("rect")
- .attr("x",width)
- .attr("y",function(d,i){ return i * 20;})
- .attr("width",10)
- .attr("height",10)
- .style("fill",function(d) {
- return color.domain(d3.keys(d[0]).filter(function(key) { return key !== "day"; }));
- });
- legend.selectAll('text')
- .datum(function(d) { return {name: d.name,value: d.values[d.values.length - 1]}; })
- .append("text")
- .attr("x",i){ return i * 20 + 9;})
- .text(function(d) {
- return d.name;
- });
到代码结尾,键名(d.name)与我的数据格式相符,但不显示.有一点,它显示了图表右侧的所有黑框,这意味着我很近,但我错过了一些重要的事情
任何洞察力赞赏
解决方法
Here是一个固定&您的代码重构版本.
- var legend = svg.selectAll('g')
- .data(cities)
- .enter()
- .append('g')
- .attr('class','legend');
- legend.append('rect')
- .attr('x',width - 20)
- .attr('y',i){ return i * 20;})
- .attr('width',10)
- .attr('height',10)
- .style('fill',function(d) {
- return color(d.name);
- });
- legend.append('text')
- .attr('x',width - 8)
- .attr('y',i){ return (i * 20) + 9;})
- .text(function(d){ return d.name; });
您需要使用enter(),但是输入()和exit()方法不能与datum()一起使用.从d3 wiki起
selection.datum([value])
Gets or sets the bound data for each selected element. Unlike the selection.data method,this method does not compute a join (and thus does not compute enter and exit selections).