Home > Mobile >  Bar graph bleeding below y axis D3.js
Bar graph bleeding below y axis D3.js

Time:02-02

I can't figure out why my elements are bleeding into the bottom padding. It is preventing me from having a elements. I am sure it is something simple, it always is. I just can't figure out what's wrong. I have tried changing the height and the scales, but it just changes things I don't want changed. I keep looking at tutorials on scales and I haven't found anything that seems off. If I get I have the project on codepen, here is the link: enter image description here

Here is the javascript:

  //Mapping dataset to its x and y axes
  const xData = dataset.map(d => {
    let date = new Date(d[0]);
    return date;
  });
  
  const xDates = xData.map(d => {
    let dateFormatted = d.toLocaleString("default", {month: "short"})   ' '   d.getDate()   ', '   d.getFullYear()
    return dateFormatted;
  });
  
  const yData = dataset.map(d => d[1]);
  //Variable for use inside D3
  const h = 400;
  const w = 800;
  const pad = 40;
  
  //Scales for the SVG element
  const xDateScale = d3.scaleTime()
                .domain([0, w])
                .range([pad, w - pad]);
  const xScale = d3.scaleLinear()
                .domain([0, yData.length])
                .range([pad, w - pad]);
  const yScale = d3.scaleLinear()
                .domain([0, d3.max(yData, (d) => d)])
                .range([h - pad, pad]);

  //Declaring the SVG element
  const svg = d3.select('#svg-container')
                .append('svg')
                .attr('width', w)
                .attr('height', h)
  
  //Declaring each bar
  svg.selectAll('rect')
      .data(yData)
      .enter()
      .append('rect')
      .attr('x', (d, i) => xScale(i))
      .attr('y', (d, i) => yScale(d))
      .attr("width", w / (yData.length - pad * 2))
      .attr("height", (d, i) => d)
      .attr("class", "bar")
      .append('title')
      .text((d, i) => 'GDP: '   d   ' | Date: '   xDates[i])
 
  //Axes Declarations
  const xAxis = d3.axisBottom(xDateScale);
  const yAxis = d3.axisLeft(yScale);
    
  svg.append("g")
      .attr("transform", "translate(0,"   (h - pad / 2)   ")")
      .call(xAxis);
  svg.append("g")
      .attr("transform", "translate("   pad   ",0)")
      .call(yAxis)

CodePudding user response:

The problem is that you're not using the correct value with the height attribute for your rects

Just make the following change and it should work:

.attr("height", (d, i) => yScale(0) - yScale(d))
  •  Tags:  
  • Related