【问题标题】:d3.js: Labels are not respecting their place (simple bar chart)d3.js:标签不尊重他们的位置(简单的条形图)
【发布时间】:2014-09-04 19:58:44
【问题描述】:

我正在研究 Scott Murray 的 exercise from Chapter 9 of his book - 具体来说,使用更新选择来引入新数据点。他用一个简单的条形图演示它,然后将更新标签作为练习。作为免责声明,我几乎是一个完整的 d3 菜鸟。

所以当每个新数据点到达时,我已经设法让标签过渡到图表上。但是,出于神秘的原因,他们并没有把自己放在每个酒吧的中心。奇怪的是,旧的原始数据点的条形标签 - 只有新的不起作用。这是它的样子(新数据从右侧滑入):

这是我的代码:

            var labels = svg.selectAll("text")
                .data(dataset);


            labels.enter()
                .append("text")
                .text(function(d) {
                    return d;
                    })
                .attr("x", w)
                .attr("y", function(d) {
                    return h - yScale(d) + 14;
                    })
                .attr("font-family", "sans-serif")
                .attr("font-size", "11px")
                .attr("fill", "white");


            labels.transition()
                .duration(500)
                .text(function(d) {
                    return d;
                })
                .attr("x", function(d, i) {
                    return xScale(i) + xScale.rangeBand() / 2 ;
                })
                .attr("y", function(d) {
                    return h - yScale(d) + 14;
                });

我的直觉是第三部分出了问题 - 在labels.transition() 之后,特别是我的xScale.rangeBand() / 2 业务发生了问题。但任何见解都会非常受欢迎!

【问题讨论】:

    标签: d3.js


    【解决方案1】:

    标签放置正确。您应该将属性 text-anchor 设置为 middle 以使标签水平居中。

        labels.enter()
            .append("text")
            .attr("text-anchor", "middle")
            .text(function(d) {
                return d;
                })
            .attr("x", w)
            .attr("y", function(d) {
                return h - yScale(d) + 14;
                })
            .attr("font-family", "sans-serif")
            .attr("font-size", "11px")
            .attr("fill", "white");
    

    学习愉快!

    【讨论】:

    • 真棒 - 工作。谢谢,巴勃罗。我错过了原始标签上较早的 text-anchor .attr。
    猜你喜欢
    • 1970-01-01
    • 2014-01-20
    • 2020-11-05
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2017-08-04
    相关资源
    最近更新 更多