【问题标题】:Histogram with D3 , bars are not fitting hight of svg带有 D3 的直方图,条形图不适合 svg 的高度
【发布时间】:2020-10-23 11:45:49
【问题描述】:

我正在根据数据(动态变化)绘制直方图,但某些条形的高度不适合 svg 区域(超出 svg 区域) 这是我怀疑的一段代码:

private drawBars(data: any[]): void {
    let f = Math.min.apply(Math, this.fixedData.map(function (o) {
        return o.xAxis;
    }));
    /** Create the X-axis band scale */
    const x = d3.scaleBand()
        .range([f, 240])
        .domain(data.map(d => d.xAxis))
        .padding(0);

    /** Create the Y-axis band scale */
    const y = d3.scaleLinear()
        .domain([0, this.axisMax])
        .range([this.height, 0])
        .nice();


    /** Create and fill the bars */
    this.svg.selectAll("*").remove()
    this.svg.selectAll("bars")
        .data(data, d => d)
        .enter()
        .append("rect")
        .attr("x", d => x(d.xAxis))
        .attr("y", d => y(d.yAxis))
        .attr("width", x.bandwidth())
        .attr("height", (d) => this.height - y(d.yAxis))
        .attr("fill", (d) => this.colorPicker(d))
}

这是这种奇怪行为的证明:

任何想法,我将不胜感激!

【问题讨论】:

  • 请注意,多个数据的行为相同
  • 看起来this.axisMax 太低了。您能否检查该值是否计算正确?

标签: javascript svg d3.js histogram


【解决方案1】:

您的问题是由this.axisMax 设置得太低引起的,这里:

    const y = d3.scaleLinear()
        .domain([0, this.axisMax])
        .range([this.height, 0])
        .nice();

您需要根据可用数据重新计算。

规模的域包含它接受的可能值的范围,但至少对于scaleLinear、scaleTime 和其他一些人,超出该范围不会引发错误甚至返回NaN .对于这些类型的尺度,域用于识别输入值和输出像素之间的线性变换。

例如

假设您有一个域 [0, 10] 和范围 [0, 100] 的线性刻度。然后,x = 0 给出像素值0,x = 10 给出100。但是,x = 20 给出的像素值200 超过了给定的范围。

【讨论】:

  • 感谢您的回答,所以域,尤其是axisMax,我可以动态分配一个值以始终适合随机范围和给定域吗?
  • 是的,只要数据发生变化(例如从服务器加载),就更新域。许多人在定义图表大小时只设置一次范围
  • 是的,我明白了,但是只要数据发生更改,this.axisMax 就会更改,这是 (x,y) 值对象数组中 yAxis 的最大值。例如对于上面的图像,我得到axisMax值为428,它低于1000(手动设置以测试它)是逻辑吗?
  • 我不明白。 428 是不是太低了,是不是给你带来了问题?
  • 那么这个计算可能是错误的。是堆积条形图吗?然后,您需要获得条形总和的最大值。或者还有其他事情发生。请分享您的代码,这只是猜测
猜你喜欢
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-22
  • 2012-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多