简体   繁体   中英

Histogram with D3 , bars are not fitting hight of svg

am plotting histogram based on Data ( which is changing dynamically ) , but the height of some bars are not fitting the svg zone ( the exceed the svg area ) this is piece of code which i have doubt on :

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))
}

and here is a proof of that weird behaviour :

在此处输入图片说明

any ideas and i would be thankful !

Your problem is caused by this.axisMax being set way too low, here:

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

You need to recalculate it based on the available data.

The domain of a scale holds the range of possible values it accepts, but, at least for scaleLinear , scaleTime , and some others, being outside that range doesn't throw an error or even return NaN . For these types of scales, the domain is instead used to identify a linear transformation between the input values and output pixels.

For example

Suppose you have a linear scale with domain [0, 10] and range [0, 100]. Then, x = 0 gives pixel value 0 , and x = 10 gives 100 . However, x = 20 gives pixel value 200 , which is more than the given range.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM