D3 chart displayed incorrectly

I have spent a couple of hours trying to understand why my chart, which is supposed to look like this, instead looks much differently, as you can see based on the code below. FYI it’s one of the FCC challenges on data visualization.
What mistake am I making here?

const svg_width = 1000;
const svg_height = 750;
const margin = {
  'top':40,
  'bottom':40,
  'left':60,
  'right': 60,
}

var svg = d3.select("#chart-container")
.append("svg")
.attr("width", svg_width)
.attr("height", svg_height)
.style("border", "solid")

d3.json("https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json", function (data) {
  var dataset = data.data
  var parseDates = d3.timeParse("%Y-%m-%d")
  
  var xScale = d3.scaleTime()
  .domain([d3.min(dataset, (d) => parseDates(d[0])),
          d3.max(dataset, (d) => parseDates(d[0]))])
  .range([margin.left, svg_width - margin.right])
  
  var xAxis = d3.axisBottom()
  .scale(xScale)
  .tickSizeOuter(0)
  
  svg.append("g")
  .attr("transform", ("translate(0," + (svg_height- margin.bottom)+")"))
  .call(xAxis.ticks(d3.timeYear).ticks(10))
  
  var yScale = d3.scaleLinear()
  .domain([d3.min(dataset, (d) => d[1]), 
          d3.max(dataset, (d) => d[1])])
  .range([svg_height - margin.bottom, margin.bottom])
  
  var yAxis = d3.axisLeft()
  .scale(yScale)
  .tickSizeOuter(0)
  
  svg.append("g")
  .call(yAxis)
  .attr("transform", "translate (60, 0)")
  
  svg.selectAll("rect")
  .data(dataset)
  .enter()
  .append("rect")
  .attr("x", (d) => xScale(parseDates(d[0])))
  .attr("y", (d) => (svg_height - margin.top) - yScale(d[1]))
  .attr("width", 1)
  .attr("height", (d) => yScale(d[1]))
  .attr("fill", "green")
});
<script src="https://d3js.org/d3.v4.min.js" charset="utf-8"></script>
<div id="chart-container"></div>

26 thoughts on “D3 chart displayed incorrectly”

Leave a Comment