I am trying to get the height of my bars scaled by a linearScale I created. I also need the text for each bar to rest on top of the bar and so am using the same linearScale to situate them in the right place.
Despite the fact that I am using the same scale, my text is situated in the right spots on the graph but my bar charts are doing the exact opposite, i.e. returning the smallest value for the largest data point and v.v.
As a check I hardcoded the height with smallest and largest values in dataset. And sure enough, when I put in the smallest value I got a larger bar than when I put in the largest.
This is driving me nuts, please help.
My code so far:
<!DOCTYPE html>
<html lang = "en">
<head>
<script src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<style>
svg {
background-color: pink;
}
.bar:hover {
fill: brown;
}
</style>
<body>
<script>
const w = 1100
const h = 300
const padding = 60
const svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h)
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick=function(){
req=new XMLHttpRequest();
req.open("GET",'https://api.worldbank.org/v2/countries/all/indicators/SP.POP.TOTL?format=json',true);
req.send();
req.onload=function(){
json=JSON.parse(req.responseText);
let yValArr = [];
for(var i = 0; i < json[1].length; i++){
yValArr.push(Math.round( ((json[1][i]["value"])/10000000) * 10) / 10)
}
document.getElementsByClassName('message')[0].innerHTML= yValArr;
const yScale = d3.scaleLinear()
.domain([0, (d3.max(yValArr) + 2)])
.range([h-padding, padding]);
svg.selectAll("rect")
.data(yValArr)
.enter()
.append("rect")
.attr("x", (d, i) => padding + (i * 30))
.attr("y", (d, i) => (h - yScale(d)) - padding)
.attr("width", 25)
.attr("height", (d, i) => yScale(d))
.attr("class","bar");
svg.selectAll("text")
.data(yValArr)
.enter()
.append("text")
.attr("x", (d, i) => padding + (i * 30) + 14)
.attr("y", (d, i) => yScale(d))
.text((d) => d)
.attr("font-size",5)
.attr("fill","red")
const yAxis = d3.axisLeft(yScale);
svg.append("g")
.attr("transform", "translate(" + (padding) + ", 0)")
.call(yAxis);
};
};
});
</script>
<br>
<button id="getMessage">
Get Data
</button>
<p class="message">
The data will go here
</p>
</body>
</html>