d3.js v4,在气泡图上为气泡添加文本标签 [英] d3.js v4, adding text labels to bubbles on a bubble chart
问题描述
我正在构建一个气泡图。图表正好显示我的喜好。我遇到的唯一问题是让文字出现在每个泡泡的中间。
I'm building a bubble chart. The chart is appearing exactly how I'd like. The only issue I have been having is getting text to appear in the middle of each bubble.
文字根本没有出现,我尝试了几个选项来实现它。当我检查页面时,每个圆圈内都有一个文本元素。但是,该元素不会出现在页面上,尽管它嵌套在每个圆圈内。我在下面粘贴我的代码。非常感谢所有帮助。
Text is not appearing at all and I have tried several options to get it there. When I inspect the page, inside of each circle there is a text element. However, the element does not appear on the page, although it is nested inside of each circle. I am pasting my code below. All help is greatly appreciated.
let width = 600;
let height = 600;
let maxRadius = d3.max(data, (data) => { return data.PercentHomeless; })
let minRadius = d3.min(data, (data) => { return data.PercentHomeless; })
let svg = d3.selectAll('section')
.append('svg')
.attr('height', height)
.attr('width', width)
.append('g')
.attr('transform', 'translate(0, 0)')
let colors = d3.scaleOrdinal(d3.schemePaired);
let simulation = d3.forceSimulation()
.force('x', d3.forceX(width/2).strength(0.5))
.force('y', d3.forceY(height/2).strength(0.5))
.force('collide', d3.forceCollide((data) => { return r(data.PercentHomeless) + 1.5; }))
let r = d3.scaleSqrt()
.domain([minRadius, maxRadius])
.range([15,75])
let circles = svg.selectAll('circles')
.data(data)
.enter()
.append('circle')
.attr('fill', (data) => { return colors(data.State); })
.attr('r', (data) => { return r(data.PercentHomeless); })
circles.append('text')
.attr("dy", ".3em")
.attr("dx", -10)
.attr("text-anchor", "middle")
.text((data) => { return data.State; })
.attr('color', 'black')
.attr('font-size', 15)
let ticked = () => {
circles
.attr('cx', (data) => { return data.x })
.attr('cy', (data) => { return data.y })
}
simulation.nodes(data)
.on('tick', ticked)
});
推荐答案
在SVG中,< circle>
不是一个容器元素,也就是说, 不能将文本附加到圈子中。当您检查页面时,您在圆圈元素中看到文本的事实没有区别:它们不会被渲染。
In SVGs, <circle>
is not a container element, that is, you cannot append texts to circles. The fact that you see the texts inside the circle elements when you inspect the page makes no difference: they will not be rendered.
解决方案:为文本创建单独的选择:
Solution: create a separate selection for the texts:
let texts = svg.selectAll(null)
.data(data)
.enter()
.append('text')
.text(d => d.State)
.attr('color', 'black')
.attr('font-size', 15)
并在<$中重新定位它们c $ c>勾选功能(根据您的需要更改其x和y位置):
And reposition them in the ticked
function (change their x and y positions according to your needs):
let ticked = () => {
circles.attr('cx', (data) => {
return data.x
})
.attr('cy', (data) => {
return data.y
});
texts.attr('x', (data) => {
return data.x
})
.attr('y', (data) => {
return data.y
});
}
这篇关于d3.js v4,在气泡图上为气泡添加文本标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!