Tell us what’s happening:
I have created a bar chart (with some example data, not real data) i.e. const dataset = [
[243.1 , 123.23],
[300.1 , 287.12],
[450.1 , 350.22],
[660.3 , 454.1],
[866.2 , 568.2]
]
Everything seems to be fine except for the face that the bar’s are inverted
And when i try to correct them only one bar gets corrected and all the others seems to be just show a bit of the part upside and everything else goes down like this:
I can’t seem to find the correct value of ‘y’ attribute of the rectangle(i.e. bar) .
Can anyone suggest something here?
Your code so far
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title id="title">United States GDP</title>
</head>
<body>
<script src="https://d3js.org/d3.v5.js"></script>
<script>
const dataset = [
[243.1 , 123.23],
[300.1 , 287.12],
[450.1 , 350.22],
[660.3 , 454.1],
[866.2 , 568.2]
]
// Set the Height of the SVG
const w = 500;
const h = 1000;
const padding = 30;
// Return the maximum value of the dataset variable
// range is the range of the xAxis like 0 - 400 or 0 - 500, whatever the case maybe
// xAxis is the horizontal line
const xScale = d3.scaleLinear()
.domain([0,d3.max(dataset, (d) => d[0])])
.range([padding, w - padding])
// yAxis is the vertical line
// Get the Maximum varibale from the first index of dataset
const yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, (d) => d[1])])
.range([h - padding, padding])
const svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h)
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", (d,i) => 30 * i)
.attr("y", 20 * 36)
.attr("width", 25)
.attr("height", (d, i) => {
return d[0] ;
})
.attr("fill", "navy")
.attr("class", "bar")
.append("title")
.text((d) =>"$" + d + " Millions")
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
// SVG is the mother of all elements in D3
// X Axis of the chart
svg.append("g")
.attr("transform", "translate(0, " + (h - padding) + ")")
.call(xAxis)
// Y Axis of the Chart
svg.append("g")
.attr("transform", "translate(" + (padding) + ",0)")
.call(yAxis)
</script>
</body>
</html>
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36
.
Challenge: Visualize Data with a Bar Chart
Link to the challenge: