我在向栏中添加文本时遇到了一些问题。我想在栏上方显示值,但我无法向每个栏添加文本。
现在我的dom结构是:
g
rect
rect
rect
我想要什么:
g
g.bar
rect
text
g.bar
rect
text
如何将父级 (g) 添加到我的矩形并将矩形和文本添加为子级?
我的代码:
bars = svg.selectAll('rect').data(datasource)
# bars enter
bars.enter().append('rect')
.attr('class', (d, i) =>
"rect-" + i)
.attr('x', (d) =>
x(d.age))
.attr('y', height)
.attr('width', x.rangeBand())
.attr('height', 0)
.attr('fill', (d) =>
d.color)
bars
.attr('fill', (d) ->
d.color)
.transition()
.delay(200)
.ease(transition_ease)
.duration(transition_duration)
.attr('y', (d) =>
y(d.value))
.attr('height', (d) =>
height - y(d.value))
bars.exit().remove()
Jsfiddle:http://jsfiddle.net/qjbgtxqu/
最佳答案
按照 Lars 的建议(总是好的建议),这是一个处理元素分组的"template"(例如 rect
和 text
下的 g
):
group = svg.selectAll('g')
.data(datasource) # bind data to g elements
group.exit()
.remove();
groupEnter = group.enter()
.append("g") # append g elements
groupEnter
.append("rect") # append rect elements
groupEnter
.append("text") # append text elements
group
... # update g elements, if needed (e.g. add transform, add listeners)
group.select("rect")
.data(datasource)
... # update the rect elements
group.select("text")
.data(datasource)
... # update the text elements
关于javascript - 将文本添加到 d3 栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26481750/