简体   繁体   中英

D3 bar chart and using multiple scales

I'm creating a "trending" analysis bar chart using d3. This chart has an X axis in the middle, and bars that can extend either above or below this axis to represent percentage change. I've done this by using 3 scales - an ordinal for the X axis, and two linear scales for the Y axis. The usage of the two linear scales is what I'm uncertain about. It seems inelegant and just "not right."

The scales in question:

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]);

Functions related to drawing the bars:

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

Is this a decent way to do this? Or is there a more elegant way using one Y scale that I'm missing?

Thanks for your time.

From your description, it sounds like you should be able to replace your two scales with one scale simply like this:

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

and use this.yscale in the rest of the code.

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