D3.js D3。。尝试向条形图添加标签时,会向每个标签添加所有值
我对D3比较陌生,正在尝试为条形图添加标签。。我一直遇到标签将所有值应用于每个标签的问题。预加此代码是正常的数据加载等D3.js D3。。尝试向条形图添加标签时,会向每个标签添加所有值,d3.js,labels,D3.js,Labels,我对D3比较陌生,正在尝试为条形图添加标签。。我一直遇到标签将所有值应用于每个标签的问题。预加此代码是正常的数据加载等 // Controls Bar Layout and Offset (x(d.weekOf)+20) var property = svg.selectAll(".property") .data(data) .enter().append("g") .attr("class", "g")
// Controls Bar Layout and Offset (x(d.weekOf)+20)
var property = svg.selectAll(".property")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) { return "translate(" + (x(d.weekOf)+20) + ",0)"; });
// Theese are the bars, width is the width of the bars
property.selectAll("rect")
.data(function(d) { return d.emissions; })
.enter().append("rect")
.attr("width", "80")
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.attr("opacity", "0.7")
.style("fill", function(d) { return color(d.name); });
// Add Capacity Labels
property.selectAll("text")
.data(data)
.enter()
.append("text")
.text(function(d, i) {return d.Internal; })
.attr("x", 41)
.attr("y", 210)
.attr("text-anchor", "middle");
很明显,我缺少了一些简单的东西。您的标签是属性选择的子选择,因此,您不应该像现在这样使用data()将每个属性标签连接到整个数据集,而应该使用数据连接到相应的父数据集,如下所示:
property.selectAll("text")
.data(function(d) {return [d];})
.enter()
.append("text")
.text(function(d, i) {return d.Internal; })
.attr("x", 41)
.attr("y", 210)
.attr("text-anchor", "middle");
这不是您要问的问题的原因,但另一个潜在问题是您正在选择“.property”,但将类设置为“g”。如果刷新数据并再次运行此代码,则每次都会创建新节点。您可能应该为“.g”选择,以便选择现有节点进行重新绑定。