Data visualization Bar Chart

What is wrong? The bars aren’t appearing.

const dataset = [
                  [ 34,     78 ],
                  [ 109,   280 ],
                  [ 310,   120 ],
                  [ 79,   411 ],
                  [ 420,   220 ],
                  [ 233,   145 ],
                  [ 333,   96 ],
                  [ 222,    333 ],
                  [ 78,    320 ],
                  [ 21,   123 ]
                ];
    const w = 500;
    const h = 500;
    const padding = 60;
    const xScale = d3.scaleLinear()
                     .domain([0, d3.max(dataset, (d) => d[0])])
                     .range([padding, w - padding]);
    const yScale = d3.scaleLinear()
                     .domain([0, d3.max(dataset, (d) => d[1])])
                     .range([h - padding, padding]);
    const svg = d3.select("body")
       .append("svg")
       .attr("width", w)
       .attr("height", h);

    svg.selectAll("rect")
       .data(dataset)
       .enter()
       .append("rect")
       .attr("x", (d, i) => i * 30)
       .attr("y", (d, i) => h - 3 * d)
       .attr("width", 25)
       .attr("height", (d, i) => d * 3)
       .attr("fill", "purple")
       .attr("class", "bar")
    const xAxis = d3.axisBottom(xScale);
    
    const yAxis = d3.axisLeft(yScale);
    
    svg.append("g")
       .attr("transform", "translate(0," + (h - padding) + ")")
       .call(xAxis);
    svg.append("g")
       .attr("transform", "translate(" + padding + ",0)")
       .call(yAxis)

Adding a link to the assignment or project would be helpful for debugging.

The main problem is likely code like this:

Log the d and you’ll probably get something like [ 34, 78 ] as the first value since that is the first value in dataset. You’ll need to change the code if you just want the 34 or the 78.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.