javascript - d3 bar label on grouped chart bar
问题描述
Im using this example - https://bl.ocks.org/bricedev/0d95074b6d83a77dc3ad
and trying to add adittional infromation on the bars.
I tried:
slice.selectAll("rect").append("text")
.attr("class", 'bar-text')
.attr("fill", "#000")
.text(function (d) {
return d.total;
})
.attr("transform", function (d, i) {
var x0 = x1.rangeBand() * i + 11,
y0 = y + 8;
return "translate(" + x0 + "," + y0 + ")";
})
But text elements appends to inner rect element and it is not visible:
<g class="g" transform="translate(46,0)">
<rect width="101" x="2" style="fill: rgb(8, 81, 156);" y="150.00000000000003" height="300">
<text class="bar-text" fill="#000" transform="translate(11,function u(n){return o(n)}8)"></text>
</rect>
<rect width="101" x
...
slice.append... selects only groups unfortunately too. Any ideas how to append text element on this example to bars?
解决方案
Have a look at your screenshot, the translate
attribute contains function u(n)....
. The variable y is a function not the value of the rect Y-coord. To get that you need d3.select(this).attr("y")
. But then the text is also not visible I used y(d.value)
but that is equivalent.
You have to add the texts just like the rects.
This you need to add to the d3v5 code I posted in https://stackoverflow.com/a/51573685/9938317
The text does not animate yet, use the same animation code as for the rect Y-coord. Or create the text at the end of the rect animation.
slice.selectAll("text")
.data(function(d) { return d.values; })
.enter().append("text")
.attr("class", 'bar-text')
.attr("fill", "#000")
.attr("text-anchor", "middle")
.text(function (d) { return d.value; })
.attr("x", function (d, i) { return x1.bandwidth() * (i+0.5); })
.attr("y", function (d, i) { return y(d.value) + 8; });
推荐阅读
- json - Kafka Connect:读取 JSON 序列化的 Kafka 消息,转换为 Parquet 格式并保存在 S3 中
- c - 函数声明中 '(const struct namect*)' 背后的含义是什么?
- java - 如何以多线程方式从 Java 代码运行 JMTER 脚本 (JMX)
- angular - Angular 11 选择了 mat-select 的默认值,填充了 observable
- reactjs - useEffect() 和 Google Firebase onAuthStateChange
- python - 使用 cursor.execute 到 pandas 的 SQL 行
- r - 陷入错误:软件包“XXXXX”的编译失败
- flutter - Flutter 错误:-RenderBox 和滚动范围为负数,如果没有视频,如何隐藏小部件?
- node.js - axios 获取post返回页面的重定向URL
- android - 嗨,我正在尝试克隆 trello,但在创建板时出现错误