D3.Js Area Chart creating a vertical instead of a horizontal fill

27 views Asked by At

I am trying to make a basic area chart showing the change in death over time. My goal is to have the area char fill the area from the data point to the bottom of the x-axis. However, the area from the data point to the y-axis seems to be filling instead. I am not sure why this is occurring or how to fix it.

If anyone could guide me on how to modify the code or explain why this filling behavior is happening, it would be greatly appreciated. My ultimate goal is to visualize the accumulation of deaths over time correctly, with the area filled from each data point down to the X-axis, rather than to the Y-axis.

Thank you for your help!

Please see image below of my current output

enter image description here

###Here is my code

 /* CONSTANTS AND GLOBALS */
 const width = window.innerWidth * 0.7,
   height = window.innerHeight,
   margin = { top: 20, bottom: 50, left: 100, right: 60 };

/* LOAD DATA */
d3.csv('../data/New_York_City_Leading_Causes_of_Death.csv', d => {
  return {
     //Year: new Date(+d.Year, 0, 1), // Remove commas from Year,
     Year: +d.Year, // Remove commas from Year,
     Deaths: +d.Deaths
  }
}).then(data => {
  console.log('data :>> ', data);

  // SCALES
  const xScale = d3.scaleLinear() 
    .domain(d3.extent(data, d => d.Year))
    .range([margin.left, width-margin.right])

  const yScale =  d3.scaleLinear()
    .domain(d3.extent(data, d => d.Deaths))
    .range([height - margin.bottom, margin.top])

  // CREATE SVG ELEMENT
  const svg =d3.select("#container")
    .append("svg")
    .attr("width", width)
    .attr("height", height)
    .style("background-color", "aliceblue")

  // BUILD AND CALL AXES
const xAxis = d3.axisBottom(xScale).tickFormat(d3.format("d"))

const xAxisGroup = svg.append("g")
  .attr("class", "xAxis")
  .attr("transform", `translate(${0},${height - margin.bottom})`)
  .call(xAxis)

xAxisGroup.append("text")
  .attr("class", 'xLabel')
  .attr("transform", `translate(${width}, ${35})`)
  .text("Year") 

const yAxis = d3.axisLeft(yScale)
// .tickFormat(formatBillions)

const yAxisGroup = svg.append("g")
  .attr("class", "yAxis")
  .attr("transform", `translate(${margin.left}, ${0})`)
  .call(yAxis)

// AREA GENERATOR FUNCTION
const areaGen = d3.area()
  .x(d => xScale(d.Year))
  .y0(yScale(0)) // Set the bottom of the area to the bottom of the chart
  .y1(d => yScale(d.Deaths))

svg.append("path")
  .datum(data)
  .attr("fill", "#7FFFD4")
  .attr("stroke", "#B22222")
  .attr("stroke-width", 1.5)
  .attr("d", areaGen(data));
  
});
0

There are 0 answers