Hello amazing community at Stack Overflow,
I've been working on a project for my university where I am trying to create a bar chart using d3v7. I have been following the example from the Blocks
but I keep encountering an error mentioned in the title of this question. It seems that my code is struggling to read the data properly, and despite my efforts, I am unable to resolve this issue. Your assistance in solving this problem would be greatly appreciated.
Below is the code I have written:
var margin = {top: 5, right:10, bottom:5, left:10},
width = 575 - margin.left - margin.right,
height = 200 - margin.top - margin.bottom;
// set the ranges
var x = d3.scaleBand()
.range([0, width])
.padding(0.1);
var y = d3.scaleLinear()
.range([height, 0];
// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("#bar").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// get the data
d3.csv("canton_pop.csv").then(function(data) {
// format the data
data.forEach(function(d) {
d.Population = +d.Population;
});
// Scale the range of the data in the domains
x.domain(data.map(function(d) { return d.Canton; }));
y.domain([0, d3.max(data, function(d) { return d.Population; })]);
// append the rectangles for the bar chart
svg.selectAll(".bar_chart")
.data(data)
.enter().append("rect")
.attr("class", "bar_chart")
.attr("x", function(d) { return x(d.Canton); })
.attr("width", x.bandwidth())
.attr("y", function(d) { return y(d.Population); })
.attr("height", function(d) { return height - y(d.Population); });
// add the x Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// add the y Axis
svg.append("g")
.call(d3.axisLeft(y));
});
Below is the data in my CSV file:
Canton;Population
Zürich;1553423
...
Jura;73709
When I run my code, I am unable to see any bars on the chart, and the axis does not have any labels (see image for reference). Any help in resolving this issue would be appreciated.
Resulting bar chart: https://i.sstatic.net/EhaG8.jpg
The error message in my console: https://i.sstatic.net/FQ2Vw.png