【问题标题】:D3 bar chart and using multiple scalesD3 条形图并使用多个刻度
【发布时间】:2014-03-02 03:03:56
【问题描述】:

我正在使用 d3 创建一个“趋势”分析条形图。该图表在中间有一个 X 轴,条形可以在该轴上方或下方延伸以表示百分比变化。我通过使用 3 个刻度来做到这一点 - X 轴的序数和 Y 轴的两个线性刻度。 两个线性刻度的使用是我不确定的。这似乎不雅,只是“不对”。

有问题的秤:

this.pyscale.domain([0, 1]);
this.pyscale.rangeRound([this.height/2, 0]);

this.nyscale.domain([-1, 0]);
this.nyscale.rangeRound([this.height, this.height/2]);

与绘制条形相关的函数:

bar.append("rect")
   .attr("y", function(d) { 
        if (d[that.ycol] >= 0) {
            return that.pyscale(d[that.ycol]);
        }
        return that.height/2; 
    })
   .attr("height", function(d) { 
        if (d[that.ycol] >= 0) {
            return that.height/2 - that.pyscale(d[that.ycol]);
        }
        return that.nyscale(d[that.ycol]) - that.height/2;
    })
   .attr("width", this.xscale.rangeBand())

这是一个不错的方法吗?或者有没有更优雅的方式使用我缺少的 Y 刻度?

感谢您的宝贵时间。

【问题讨论】:

    标签: javascript d3.js visualization


    【解决方案1】:

    根据您的描述,听起来您应该可以像这样用一个秤替换您的两个秤:

    this.yscale.domain([-1, 1]);
    this.yscale.rangeRound([this.height, 0]);
    

    并在其余代码中使用this.yscale

    【讨论】:

    • 澄清一下:您仍然需要决定是根据值(正)还是在零线(负)定位矩形的顶部:yscale( Math.max(0, d[that.ycol] ) ) 应该可以工作。对于矩形的高度,您可以使用Math.abs( yscale(d[that.ycol]) - yscale(0) )
    • 很好,我错过了!
    • 如果我们可以只使用负高度或宽度来表示“与正常方向相反的方向绘制”,代码会简单得多,但没有这样的运气。
    • 谢谢 AmeliaBR,说得通。
    猜你喜欢
    • 1970-01-01
    • 2013-09-15
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2020-08-14
    • 1970-01-01
    • 2014-08-22
    相关资源
    最近更新 更多