如何正确地使文本宽度居中图条上方的标签? [英] How to properly get text width to center labels above graph bars?
问题描述
我目前有一个图表,在每个条形上方显示相关条形值,但由于无法获取每个文本元素的宽度,我很难将值标签居中.
I currently have a graph that has associated bar values displaying above each bar, but I'm having difficulty centering the value labels, due to not being able to fetch each text element's width.
这就是我现在的图表绘制方式:
This is how my graph is drawing at the moment:
我需要做的就是减去每个文本元素宽度的一半,但我似乎无法使用以下 Coffeescript 这样做:
All I need to do is to subtract half of each text element's width, but I can't seem to do so with the following Coffeescript:
#Drawing value labels
svg.selectAll("rect")
.data(data)
.enter()
.append("text")
.text((d)-> d.Total)
.attr("width", x.rangeBand())
.attr("x", (d)->
textWidth = d3.selectAll("text").attr("width")
x(d.Year) + (x.rangeBand() / 2) - (textWidth / 2)
)
.attr("y", (d)-> y(d.Total) - 5)
.attr("font-size", "10px")
.attr("font-family", "sans-serif")
#Drawing bars
svg.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d)-> x(d.Year))
.attr("width", x.rangeBand())
.attr("y", (d)-> y(d.Total))
.attr("height", (d)-> height - y(d.Total))
有没有办法可以访问每个文本元素的宽度属性来设置偏移值?
Is there a way that I can access each text element's width attribute to set a value to offset?
推荐答案
您可以获取文本的边界框并使用这些值应用变换以使其居中.here 是获取边界框的示例.代码看起来像
You can get the bounding box of the text and use those values to apply a transform to center it. An example for getting the bounding box is here. The code would look something like
.text(function(d) { return d.Total; })
.attr("x", function(d) {
return x(d.Year) + (x.rangeBand() / 2) - (this.getBBox().width / 2);
}
...
这篇关于如何正确地使文本宽度居中图条上方的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!