(SOLVED) D3 Data drawing to bottom of SVG

Working on first D3 project and my bars are drawing to the bottom of the SVG no matter where I put them (have tested by translating them upward). As a result they clip through the bottom of the scale to the bottom of the container.

Here is the code (ignore the X scaling, was just to get data showing for now):

const W = 800;
const H = 400;
const padding = 40;
const svg = d3.select("body").append("svg").attr("width", W).attr("height", H);

   let GDP = data.data.map(function (item) {
     return item[1];
   let year = data.data.map(function(item) {
     return item[0].substring(0,4);
  const barWidth = W/year.length;
  const xScale = d3.scaleLinear().domain([0, year.length]).range([padding, W - padding]);
  const yScale = d3.scaleLinear().domain([0, d3.max(GDP)]).range([H - padding, padding]);
  const xAxis = d3.axisBottom(xScale);
  const yAxis = d3.axisLeft(yScale);
   svg.selectAll("rect").data(GDP).enter().append("rect").attr("x", (d, i) => xScale([i])).attr("y", (d) => yScale(d)).attr("width", barWidth).attr("height",(d) => d);
   svg.append("g").attr("transform","translate(0, " + (H - padding) + ")").call(xAxis);
   svg.append("g").attr("transform", "translate(" + (padding) + ",0)").call(yAxis);


I wasn’t scaling my height so even though they were positioned correctly it was falling off the bottom of the screen.


1 Like