Having trouble interpreting bar chart with d3js v7. Issue: <rect> attribute height not meeting expected length, displaying as "NaN"

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

Answer №1

After some investigation, I discovered that the issue stemmed from my CSV file. I had been mistakenly using a semi-colon ";" as a delimiter instead of a comma ",".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function window.addEventListener('load') functions properly on desktop computers, but does not work on mobile devices

After developing a react website, I noticed that it functions correctly on PC but not on Mobile devices. componentDidMount() { window.addEventListener('scroll', this.onScroll); // This event works fine window.addEventListener('load&a ...

What is the best way to implement sorting in a table using react virtualized?

I've been working on implementing sorting in my project using the table sorting demo available on Github. Here is the code I'm using: import React from 'react'; import PropTypes from 'prop-types'; import { Table, Column, Sor ...

The server remains unreachable despite multiple attempts to send data using Angular's $http

I am encountering an issue with triggering $http.post: app.controller('editPageController', function($scope, $routeParams, $http) { $scope.page = $routeParams.pageid; // retrieve page data from the server $http.get('/pages/&ap ...

Implementing long-lasting login functionality in React using JSON Web Tokens

Currently, I have developed an application using React client/Express API with functioning Authentication. Users are able to register and login successfully. My next step is to implement persistent login using JWT tokens so that when a user accesses the U ...

Having issues with jQuery's .hover and .mouseleave functions causing unintentional looping. Any suggestions on how to resolve this

What I want to achieve: When hovering over the image, it fades out. Text should fade in after the image fades out. Text should fade out when the mouse leaves. The original image should fade back in. End with the original image and no text displayed. Iss ...

Chip component in Material UI for Meteor/React not recognizing the onRequestDelete method

I'm currently integrating Material UI's chip element into my application and as per the documentation onRequestDelete - Callback function triggered when the delete icon is clicked. If specified, the delete icon will be displayed. import React f ...

On mobile devices, the code "location.assign(url)" may occasionally redirect to an incorrect URL, despite functioning correctly in the majority of instances

After setting up a page with a timeout that should automatically redirect to a specific URL after 60 minutes, I encountered an issue where the redirection sometimes leads to a loss of parameters in the URL. The JavaScript code added for this purpose is set ...

Can you explain the meaning of arguments[0] and arguments[1] in relation to the executeScript method within the JavascriptExecutor interface in Selenium WebDriver?

When utilizing the executeScript() method from the JavascriptExecutor interface in Selenium WebDriver, what do arguments[0] and arguments[1] signify? Additionally, what is the function of arguments[0] in the following code snippet. javaScriptExecutor.ex ...

Displaying a loading spinner using JQuery while content is being loaded into a div

I have a navigation bar with links that load content from corresponding HTML pages into a div next to the navigation bar when clicked. To make it more user-friendly, I want to display a spinner while the content is loading. However, the current code I trie ...

In jQuery, there seems to be an issue where the click event is not functioning properly on an element that has been

I am using jQuery to append items, but I am having trouble binding events to the appended items. My appending code looks like this: var item = '<div id="'+newInputId+'" class="col-md-9" style="padding-right: 0px; ...

What is an alternative way to display static images in Rails 5 without relying on the Asset Pipeline?

I developed a web-based application with the backend built on Rails 5. Utilizing AngularJS for the frontend, I opted to not use the Asset Pipeline to deliver static content. Instead, I loaded all my scripts (JS & CSS) in the index.html file located within ...

Creating a dynamic list filter using JavaScript and three select boxes

Looking for a way to implement a similar feature to the one on this webpage: I will be showcasing a list of brands on the page, with each brand requiring three pieces of information: Starting letter Store (multiple options) Category (multiple options) ...

Why is it necessary in JavaScript to reset the function's prototype after resetting the function prototype constructor as well?

Code is often written in the following manner: function G() {}; var item = {...} G.prototype = item; G.prototype.constructor = G // What is the purpose of this line? Why do we need to include G.prototype = item before resetting the prototype? What exact ...

Modifying a csv file that's currently open

Is there a way to modify the content of a CSV file before passing it to the CSV reader? csvfile = open(input, mode='r', newline='', encoding='utf-8') # opening csv file for line in csvfile: line = line.replace(",", ";") ...

Dynamic views loaded from ui-router can cause compatibility issues with running Javascript

Currently, I am facing an issue while attempting to load a template into a UI-View using UI-Router. Although the JavaScript is loaded, it does not run on the loaded views. The situation unfolds as follows: I have developed a template in HTML containing all ...

Transforming a CSV file into JSON format using Gatsbyjs

I am currently exploring the possibilities of GatsbyJs and considering the utilization of the gatsby-transformer-csv plugin. You can find the documentation for this plugin here. I have got my hands on two CSV files exported from WordPress that I am eager ...

Is there a way to properly direct to an internal page while utilizing [routerLink] and setting target="_blank" without triggering a full page reload?

I'm attempting to use [routerLink] along with target="_blank" to direct to an internal page without triggering a full app reload. Currently, the page opens in a new tab, but the whole application is refreshed. Here is the HTML: <a [routerLink]=" ...

The callback for AJAX was unsuccessful

Using ajax to update form data in the database, a success response is expected but it's not functioning as intended. html <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> ...

Using angular2's ngRepeat to iterate over XML data

I have successfully transformed my XML data into JSON format to be utilized in Angular 2 within my view. However, as I attempt to loop through the data using a for(var... loop, I encounter an error message stating that it cannot find name array and that th ...

Struggling to employ JavaScript events when submitting a form to verify the fields

My goal is to create a form with fields that have real-time validation using JavaScript. I have achieved this by utilizing Java events in the following way: Text field onkeyup: This event sends a request to check for errors in the field every time a key ...