Working on the bar chart here.
So many axis issues. Y axis starts to low, doesn’t have ticks, Y and X axis info appears to be switched (i.e., I want X axis for years, but it seems to reflect GDP, based on the ticks). And of course they don’t line up with the rects. I’ve read through a few off-site tutorials, and looked at the questions in the forums here, but code that I think is the same is obviously not functioning correctly. Any help appreciated.
Code:
d3.json("https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json").then(function(data){ //console.log(data["data"]);
const dataset = data["data"];
console.log(dataset[0], dataset.length, "got data")
let gdps = dataset.map(function(item) {
return item[1];
})
let dates = dataset.map(function(item) {
return item[0];
})
const barWidth = 2,
barHeight = 1,
svgWidth = barWidth * gdps.length,
svgHeight = 500,
margin = 50;
const scale = d3.scaleLinear()
.domain([d3.min(gdps), d3.max(gdps)])
.range([0, svgHeight]);
const svg = d3.select("body")
.append("svg")
.attr("width", svgWidth + margin)
.attr("height", svgHeight + margin);
const y_axis = d3.axisLeft()
.scale(scale);
const x_axis = d3.axisBottom()
.scale(scale);
svg.append("g")
.attr("transform", "translation("+ margin + ", 0)")
.call(y_axis)
.attr("id", "y-axis");
svg.append("g")
.attr("transform", "translate(0, " + (svgHeight - margin) +")")
.call(x_axis)
.attr("id", "x-axis");
svg.selectAll("rect")
.data(gdps)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", (d, i) => i * barWidth + margin)
.attr("y", (d, i) => svgHeight - scale(d) - margin)
.attr("width", barWidth)
.attr("height", (d, i) => scale(d))
.attr("fill", "navy")
.attr("data-gdp", (d) => d);
type or paste code here