Home > Blockchain >  When applying the Y axis using d3, it throws an error
When applying the Y axis using d3, it throws an error

Time:11-20

I am making a simple bar chart and am currently trying to add the Y axis. When I try to use the call() function, it throws an error.

d3.v7.min.js:2 Error: <path> attribute d: Expected number, "M-6,NaNH0VNaNH-6".

Does anyone know what's wrong? I provided my code bellow.

let dataNumsOnly = [];
let labels = [];

fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
    .then(response => response.json())
    .then(data => {
        let dataForChart = data;
        dataForChart = dataForChart.data;
        for (let i = 0; i < dataForChart.length; i  ) { //grabs data and labels.
            dataNumsOnly.push(dataForChart[i][1]);
            labels.push(dataForChart[i][0]);
        }

    let svg = d3.select('body')
    .append('svg')
    .attr('width', 962)
    .attr('height', 600);

    svg.selectAll('rect')
    .data(dataNumsOnly)
    .enter()
    .append('rect')
    .attr('width', 3)
    .attr('height', d => d / 32)
    .attr("x", (d, i) => i * 3.5)
    .attr('y', d => 600 - d / 32)
    .style('fill', "rgb(51, 173, 255)");

    let yScale = d3.scaleLinear()
    .domain(0, 100)
    .range(600, 0);
    
    const yAxis = d3.axisLeft()
    .scale(yScale);
    svg.append('g')
    .call(yAxis);
    });

Thank you.

CodePudding user response:

Never mind, I got it! I forgot the brackets for the domain and range!

let dataNumsOnly = [];
let labels = [];

fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
    .then(response => response.json())
    .then(data => {
        let dataForChart = data;
        dataForChart = dataForChart.data;
        for (let i = 0; i < dataForChart.length; i  ) { //grabs data and labels.
            dataNumsOnly.push(dataForChart[i][1]);
            labels.push(dataForChart[i][0]);
        }

    let svg = d3.select('body')
    .append('svg')
    .attr('width', 962)
    .attr('height', 600);

    svg.selectAll('rect')
    .data(dataNumsOnly)
    .enter()
    .append('rect')
    .attr('width', 3)
    .attr('height', d => d / 32)
    .attr("x", (d, i) => i * 3.5)
    .attr('y', d => 600 - d / 32)
    .style('fill', "rgb(51, 173, 255)");

    let yScale = d3.scaleLinear()
    .domain([0, 1000])
    .range([600, 0]);
    
    const yAxis = d3.axisLeft()
    .scale(yScale);

    svg.append('g')
    .attr('transform', 'translate(1)')
    .call(yAxis)
    });
  • Related