[英]How to append text dynamically after rect has been created
矩形值的动态代码:
g.append('g')
.selectAll('g')
.data(data)
.enter()
.append('g')
.attr('transform', d => 'translate(' + x0(d.State) + ',0)')
.selectAll('rect')
.data(d => keys.map(key => {return {key: key, value: d[key]}}))
.enter().append('rect')
.attr('x', d => x1(d.key))
.attr('y', d => y(d.value))
.attr('width', x1.bandwidth())
.attr('height', d => innerHeight - y(d.value))
.attr('fill', d => z(d.key))
.append('text')
.text(function(d) { return d.value; })
结果看起来像:
<g transform="translate(44,0)"><rect x="11" y="0" width="185" height="420" fill="#333333"></rect>
<rect x="206" y="0" width="185" height="420" fill="#3490e9">
<text>1</text>
</rect>
<rect x="401" y="420" width="185" height="0" fill="#ff5a00">
<text>0</text>
</rect>
<rect x="596" y="420" width="185" height="0" fill="#9932CC">
<text>0</text>
</rect>
</g>
预期结果是:
<g transform="translate(44,0)">
<rect x="11" y="0" width="185" height="420" fill="#333333"></rect>
<text>1</text>
<rect x="206" y="0" width="185" height="420" fill="#3490e9">
</rect>
<text>1</text>
<rect x="401" y="420" width="185" height="0" fill="#ff5a00">
</rect>
<text>1</text>
<rect x="596" y="420" width="185" height="0" fill="#9932CC">
</rect>
<text>0</text>
</g>
我需要所有矩形之外的text
。 因为文本值未出现在条形图中。
我已经尝试过使用afterinsert进行尝试,但是没有运气
也试过像
g.append('text')
.text(function(d) { return d.value; })
但它只在g之外创建1个text element
反正g
是我的svg
由于D3的方法链接,您将text
元素嵌套在rect
元素中,其中函数返回要对其进行操作的元素(只要这些函数用于设置值)。 这意味着,当您拥有类似于您的链功能时(在此简化):
.append('g') ... .selectAll('rect').data([data]).enter() .append('rect') ... .append('text')
然后,您首先添加g
,然后为数组中的每个数据点添加一个rect
元素,最后将text
元素添加到每个rect
元素
有两种方法可以到达想要去的地方。 话虽如此,您不会获得概述的确切DOM表示,但是可以实现相同的效果。
我建议的方法是将每个数据点的rect
和text
元素成对分组在g
元素中,如下所示:
const outerG = g.append('g') .selectAll('g') .data(data) .enter() .append('g') .attr('transform', d => 'translate(' + x0(d.State) + ',0)') const pairG = outerG.selectAll('g') .data(d => keys.map(key => {return {key: key, value: d[key]}})) .enter().append('g') pairG.append('rect') .attr('x', d => x1(d.key)) .attr('y', d => y(d.value)) .attr('width', x1.bandwidth()) .attr('height', d => innerHeight - y(d.value)) .attr('fill', d => z(d.key)) pairG.append('text') .text(function(d) { return d.value; })
这将首先为每个数据点附加一个g
元素,并将对这些g
元素的引用存储在pairG
。 然后,我们将rect
元素和text
元素分别追加到pairG
变量。 这是可行的,因为D3使用于添加前一个g
的数据点可用于rect
和text
元素。 如果我们要执行一个新的.selectAll('foo').data([data]).enter().append('foo')
序列,则情况并非如此,因为这会引入新的数据点。
尽管我不确定,因为我无法访问所使用的数据,小数位数和变量,所以我插入的代码应该可以处理您的数据和设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.