iggirex
iggirex

Reputation: 113

yScale not acting consistently d3.js

I'm drawing a bar chart with axes, and yScale is behaving differently on my yAxis than on my appended bars.

I set my yScale range to start at (h - yPadding) to leave extra room at the bottom for xAxis labels.

                var yScale = d3.scale.linear()
                            .domain([0, d3.max(val)])
                            .range([h - yPadding, 0]);

-- The range is inverted, otherwise my yAxis labels are upside down.

When I call the yAxis using yScale, it obeys the starting point of (h - yPadding) and leaves room at the bottom.

But all the "rects" I'm appending to the chart, start at h, instead of (h - yPadding) even though I'm calling yScale on these "rects" just like on yAxis.

If I change the range to [h, 0] instead of [h - yPadding, 0], only the yAxis reacts to the change, and the bars still start at h.

Why are the bars ignoring the yScale?

    <script type="text/javascript">
        var xhr = new XMLHttpRequest();

        function makeRequest(){
            xhr.open("GET", "https://api.coinmarketcap.com/v1/ticker/", true);
            xhr.send();
            xhr.onreadystatechange = processRequest;
        }

        function processRequest(){
            console.log("testing, state: ", xhr.readyState)
            if(xhr.readyState == 4 && xhr.status == 200){
                dataset = [];
                for(var i = 0; i < 10; i++){
                    addingId = JSON.parse(xhr.responseText)[i];
                    addingId.id = i;
                    dataset.push(addingId);
                }
                console.log("this is dataset: ", dataset);
                makeChart();
            }
        }

        function makeChart(){
            var w = 1000;
            var h = 600;
            var padding = 40;
            var yPadding = 80;

            var val = [];
            dataset.forEach(function(ele){
                val.push(parseInt(ele.market_cap_usd));
            })
            var max = d3.max(val)

            var xAxisNames = []

            dataset.forEach(function(ele){ xAxisNames.push(ele.name); })
            // console.log(">>>>>>>>", xAxisNames)

            var xScale = d3.scale.ordinal()
                            .domain(d3.range(dataset.length))
                            .rangeRoundBands([padding, w - padding], 0.05)

            var yScale = d3.scale.linear()
                            .domain([0, d3.max(val)])
                            .range([h - yPadding, 0]);

            var yAxis = d3.svg.axis()
                            .scale(yScale)
                            .orient("left")
                            .tickFormat(function(d){
                                if(d > 0){ return d / 1000000000 + " b"; }
                                return "";
                            })

            var xAxis = d3.svg.axis()
                            .scale(xScale)
                            .orient("bottom")
                            .tickFormat(function(d, i){
                                return xAxisNames[i]
                            })

            var svg = d3.select("body")
                        .append("svg")
                        .attr("width", w)
                        .attr("height", h);

            svg.selectAll("rect")
                .data(dataset)
                .enter()
                .append("rect")
                .attr("x", function(d, i){
                    return xScale(i);
                })
                .attr("y", function(d){
                    return yScale(d.market_cap_usd);
                })
                .attr("width", xScale.rangeBand())
                .attr("height", function(d, i){
                    return h - yScale(d.market_cap_usd)
                })

            svg.append("g")
                .attr("class", "y axis")
                .attr("transform", "translate(" + padding + ", 0)")
                .call(yAxis);

            svg.append("g")
                .attr("class", "x axis")
                .attr("transform", "translate(0, " + (h - yPadding) + ")")
                .call(xAxis)
                .selectAll("text")
                .attr("y", 15)
                .attr("font-size", 12)
                .attr("x", xScale.rangeBand() / 2)
                .attr("transform", "rotate(45)")
        }

        makeRequest();

    </script>

Upvotes: 1

Views: 779

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

A scale just maps an input domain to an output range, nothing more. You have to set the positions and the dimensions of the SVG elements accordingly. Let's see:

Right now, given your scale, when you pass it the minimum value in your domain it will return:

h - yPadding

You want such bars having a height of zero pixels, of course. To get that zero the equation is simple, you have to subtract from that value:

(h - yPadding) - yScale(minimumDomainValue)

That will give you zero for the minimum value in the domain.

Therefore, this should be the height of the rectangles:

.attr("height", function(d, i){
    return (h - yPadding) - yScale(d.market_cap_usd)
})

PS: by the way, in D3, one of the few situations where a scale determines the dimensions​ of a SVG element is the path/lines created by an axis generator. That's why you're seeing a different behaviour in your axis.

Upvotes: 1

Related Questions