2016-01-23 54 views
1

我需要帮助设置D3堆叠条形图上的标签。我不知道如何将图例中的颜色与数据对象中name属性的引用进行映射。D3在图例上设置标签

我这里有一个的jsfiddle: http://jsfiddle.net/Lhs3e7xk/1/

特别是我需要帮助的代码是传说功能:

function updateLegend(dt) { 
    var legend = svg.selectAll(".legend") 
    .data(color.domain()) // I tried dt as well. 
    .enter().append("g") 
    .attr("class", "legend") 
    .attr("transform", function(d, i) { 
     return "translate(0," + i * 20 + ")"; 
    }); 

    legend.append("rect") 
     .attr("x", width - 18) 
     .attr("width", 18) 
     .attr("height", 18) 
     .style("fill", color); 

    legend.append("text") 
     .attr("x", width - 24) 
     .attr("y", 9) 
     .attr("dy", ".35em") 
     .style("text-anchor", "end") 
     .text(function(d, i) { 
     console.log(d) 
     return color(d.name) 
     }); 
} 

输出应该在数据集的名称属性的值以及与该组相关的颜色。

固定MBS [Color01]
浮动MBS [Color02]
CMO [Color03]

谢谢!

回答

1

取而代之的是

.text(function(d, i) { 
    console.log(d) 
    return color(d.name) 
    }) 

做文本功能是这样的:

.text(function(d, i) { 
    if(i==0) 
    return "Fixed MBS" 
    if(i==1) 
    return "Floating MBS" 
    if(i==2) 
    return "CMO" 

    }); 

工作实例here

编辑

对于使用数据设置的传说//您的动态图例数据集 var legends = [“固定MBS”,“浮动MBS”,“CMO”];

function updateLegend(dt) { 
    var legend = svg.selectAll(".legend") 
    .data(legends)//pass the lgend data 
    .enter().append("g") 
    .attr("class", "legend") 
    .attr("transform", function(d, i) { 
     return "translate(0," + i * 20 + ")"; 
    }); 

    legend.append("rect") 
     .attr("x", width - 18) 
     .attr("width", 18) 
     .attr("height", 18) 
     .style("fill", function(d, i){return color(i)});//color based on index 

    legend.append("text") 
     .attr("x", width - 24) 
     .attr("y", 9) 
     .attr("dy", ".35em") 
     .style("text-anchor", "end") 
     .text(function(d, i) { 
     return d;//return the array data 
     }); 
} 

工作代码here

+0

感谢西里尔,这工作,但有动态设置标签的方法吗?实际上,我可能会有超过3个部分,我也希望将此代码重用于其他图表,以便标签可能会更改。也许我可以将标签提取到不同的数组中,但理想情况下,标签应该来自数据集。没有? – vdiaz1130

+0

检查编辑部分我已经使其动态基于数组 – Cyril