我一直坚持这个代码。我正在尝试在圆圈后面添加文本 和这样的示例代码
for the text:
g.selectAll(".my-text")
.data(marks)
.enter().append("text")
.attr("class", "text-desc")
.attr("x", function(d, i) {
return projection([d.long, d.lat])[0];
})
.attr("y", function(d, i) {
return projection([d.long, d.lat])[1];
})
.attr('dy', ".3em")
.text(function() { return location})
.attr("text-anchor", "middle")
.attr('color', 'white')
.attr('font-size', 15)
and for circle like this
g.selectAll(".circle")
.data(marktests)
.enter().append("circle")
.attr("class", "bubble")
.attr("cx", function(d, i) {
return projection([d.long, d.lat])[0];
})
.attr("cy", function(d, i) {
return projection([d.long, d.lat])[1];
})
.attr("r", function() {
return myRadius(locationGroup + 20);
})
.on('mouseover', tipBranch.show)
.on('mouseout', tipBranch.hide)
.on('click', function(d){
window.open('http://localhost:8000/detail/'+d.branch);
});
}
但我得到的结果是这样的
如果您能帮助我并解释如何解决问题代码,谢谢
最佳答案
首先我注意到以下问题:
g.selectAll(".my-text")
.data(marks)
.enter().append("text")
.attr("class", "text-desc")
下面的行: .text(function() { return location})
也是错误的,因为您缺少迭代的数据对象。这可能会更改为:.text(function(d) { return d.location})
您正在选择具有类 .my-text
的所有元素,但随后将 text-desc
作为类附加到文本元素。正确的更改是:
g.selectAll(".text-desc")
.data(marks)
.enter().append("text")
.attr("class", "text-desc")
考虑到您想要使用 text-desc
作为类。同样的问题也存在于圆形:要么执行:g.selectAll("circle")
来选择圆形标签元素,要么执行g.selectAll(".bubble")
> 选择气泡。
您还对文本和圆圈使用不同的迭代对象 - 通常您应该迭代单个集合。
该示例的另一个问题是 location
和 locationGroup
不是集合项的一部分。我希望从数据对象中获取值,例如 .text( d => d.location)
和 .attr("r", d => myRadius(d.位置组))
。在继续之前,请确保使用此属性填充迭代项。
另一种方法是执行以下操作:
const group =
g.selectAll('.mark')
.data(marks)
.enter()
.append('g')
.attr('class', 'mark')
.attr('transform', d => {
const proj = projection([d.long, d.lat])
return `translate(${proj[0]}, ${proj[1]})`;
})
group.append('text').text(d => return d.location) //apply other props to text
group.append('circle').text(d => return d.location) //apply other props to circle
使用此方法将允许您使用组元素迭代集合,并使用翻译属性将组移动到该位置(小改进,投影将执行一次)并使用该组填充其他元素:文字、圆圈。
希望有帮助。
关于javascript - 文本标签隐藏在圆圈 d3 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57701949/