如何在图形条上方正确获取文本宽度到中心标签?

时间:2013-03-22 18:29:37

标签: d3.js coffeescript label bar-chart

我目前有一个图形,每个条形图上方都显示相关的条形图值,但由于无法获取每个文本元素的宽度,我很难将值标签居中。

这就是我的图表当前绘制的方式:

enter image description here

我需要做的就是减去每个文本元素宽度的一半,但我似乎无法使用以下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))

有没有办法可以访问每个文本元素的width属性来设置一个值来偏移?

2 个答案:

答案 0 :(得分:8)

一种更简单的方法是使用text-anchor middle xsvg.selectAll(".bar-label") .data(data) .enter().append("text") .text((d)-> d.Total) .attr("class", "bar-label") .attr("text-anchor", "middle") .attr("x", (d)-> x(d.Year) + x.rangeBand()/2) .attr("y", (d)-> y(d.Total) - 5) 设置在栏的左侧加上栏的宽度的一半:

conf.py

答案 1 :(得分:4)

您可以获取文本的边界框并使用这些值应用变换来居中。获取边界框的示例是here。代码看起来像

.text(function(d) { return d.Total; })
.attr("x", function(d) {
   return x(d.Year) + (x.rangeBand() / 2) - (this.getBBox().width / 2);
}
...