The D3 bar graph is displaying a height value of "Not a Number"

I'm working on incorporating a simple animated bar-chart into my webpage using the D3 (v7) library. This is part of a Django project, so the data for the chart is coming from my views.py file. However, when I try to display the chart, only part of it shows up on the page. The x and y axis lines along with the labels are visible, but there's an error message that says:

Error: <rect> attribute height: Expected length, "NaN".

Below is the relevant section from my HTML template:

<div id="chart-container"></div>

        <script src="https://d3js.org/d3.v7.min.js"></script>

        <script type="text/javascript">
          const data = JSON.parse('{{ assign_levels|safe }}');

          // Rest of the JavaScript code for generating the chart here...
      
      </script>

Additionally, here is the data input for the chart:

[["Class", 36], ["School - cluster", 6], ["Individual", 20], ["N", 1], ["School - multi-site", 9], ["Not provided/ not available", 4], ["Region or district", 1]]

I'm perplexed by the error message regarding the "NaN" height value because I've clearly set the height to an absolute value like 500 pixels in the code.

Answer №1

You've provided an array of arrays as data, but the D3 code is designed to work with an array of objects with specific keys. I have modified the data format to be an array of objects.

To make this change in your code, follow the example below:

const rawData = JSON.parse('{{ assign_levels|safe }}');
const data = rawData.map(d => ({level_assign: d[0], count: d[1]}));

This adjustment will transform your data into a structured format rather than a list of arrays.

[
  {"level_assign": "Class", "count": 36},
  {"level_assign": "School - cluster", "count": 6},
  {"level_assign": "Individual", "count": 20},
  {"level_assign": "N", "count": 1},
  {"level_assign": "School - multi-site", "count": 9},
  {"level_assign": "Not provided/ not available", "count": 4},
  {"level_assign": "Region or district", "count": 1}
]

To see an example with full code implementation:

//script.js
const rawData = [
    ["Class", 36],
    ["School - cluster", 6],
    ["Individual", 20],
    ["N", 1],
    ["School - multi-site", 9],
    ["Not provided/ not available", 4],
    ["Region or district", 1],
];

const data = rawData.map((d) => ({
    level_assign: d[0],
    count: d[1]
}));

// Rest of the D3 visualization code...
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>D3 Bar Chart</title>
</head>
<body>
    <div id="chart-container"></div>

    <script src="https://d3js.org/d3.v7.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

Answer №2

When working with the Python pandas library, you may encounter situations where an empty result is represented as NaN (which stands for "Not a Number"). To address this issue, you can utilize the fillna method to replace these NaN values with a specified value within your dataframe:

df = df.fillna('')

By implementing this change, you should be able to resolve any display problems downstream. However, it is essential to investigate further to determine why these NaN values are being generated in the first place.

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 Django error known as MultiValueDictKeyError occurs when a key

I encountered a MultiValueDictKeyError while working in Django. The issue arises when trying to logout a user from my website using the following code: In HTML </li> <li class="nav-item mr-3"> ...

Getting a value from an event listener in Node.js: Can it be done?

How can I retrieve a value from an event listener? Check out the example below: const EventEmitter = require("events").EventEmitter; emitter = new EventEmitter(); emitter.on("sayHello", function(message) { return message + " World"; }); let helloMe ...

Delivering create-react-app's build files through an express server

I am trying to serve the build files of my React app on another Express application. I have copied all the static files from the build folder to the public folder inside my Express application and have set up the following code: app.use(express.static(pat ...

Discover the magic of slide toggling with jQuery! Watch as a paragraph seamlessly appears when you click or

So, I've been working on using jQuery to display a paragraph when either hovering over or clicking the image above it. Here's what I have so far: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascr ...

How can I update jQuery CSS method on resize event?

Having trouble vertically centering a div inside the body? I've come up with a jQuery function that calculates the ideal margin-top value for achieving perfect vertical alignment. Here's how it works: Obtain container height, Get child height, ...

Ways to enable users to add or modify spry widgets

Is there a way to make it easier for users to edit spry accordions/tabbed panels in a navigation tool for locating points in PDFs? The PDFs are updated regularly, so the navigation will need frequent updates. The users who will be maintaining this tool h ...

Function that contains a JavaScript reference and observation

I'm experiencing issues with the code below and I'm having trouble figuring out what's causing the problem. function some(){ for (var i=0;i<....;i++) { var oneObject; ...some logic where this object is set oneObject.watch(prop ...

How to arrange elements at the same level in Node.js using sequelize-hierarchy?

Is there a way to change the order of items on the same level in sequelize-hierarchy for creating a menu? I've noticed that currently, the items are ordered by their sequence of insertion. But what if I want to manually set the order? Here is an exam ...

When creating a pseudo model dynamically in Django for Form initialization, it is important to exclude certain fields

Lately, I have been delving into the world of Dynamic Models and attempting to craft one myself. Taking the manual approach without relying on any pre-built helper functions, I encountered a roadblock when trying to locate the elusive create_model function ...

Accessing nodejs environment variables in a VueJS single page application

Creating a single page application with the use of Vue, running it with nodejs, and encapsulating it in a docker container poses an interesting challenge. In an attempt to adhere to the principles outlined in the 12 factor app methodology, one is advised t ...

An effective technique for retrieving multiple many-to-many objects from a queryset

I have structures that are similar to the ones shown below: class Tag(models.Model): text = models.CharField(max_length=30) class Post(models.Model): title = models.CharField(max_length=30) tags = models.ManyToManyField(Tag) A Post can be as ...

Splitting local and global config in Django settings.py file

Is there a way to segregate the "local" settings in Django (such as the local path to static files, absolute templates content, local database information, etc.) from the "global" settings (URL, middleware classes, installed apps, etc.)? This would allow m ...

Retrieving exclusive npm packages from an npmjs user

I am currently facing a challenge with transferring all of our npm modules from npmjs.com to a new location. The issue is that our modules are saved under a private npm user account, making it difficult for me to programmatically access and consume all the ...

Different ways to enhance max-http-header-size in Vue application

After being redirected from another application, I am unable to open the page and receive an error in the console: Failed to load resource: the server responded with a status of 431 (Request Header Fields Too Large). I came across information about max-h ...

Top method for preventing an HTTP 403 error when receiving the Set-Cookie header in order to establish the CSRF Cookie

As I interact with a REST API that includes CSRF protection measures, I am facing a common hurdle. Successfully obtaining the token and sending it back to the server seems to work smoothly. However, encountering an HTTP 403 error arises when initiating t ...

Triggering an event when the cursor enters a specific div/span/a element and again when the cursor exits the element

Here's the scenario - Imagine a contenteditable element with text inside. I'm working on creating a tagging feature similar to Twitter's mention tagging when someone types '@'. As the user types, a popover appears with suggestion ...

When attempting to import a component from react-bootstrap, an error is thrown

Every time I try to use a component from 'react-bootstrap', I encounter a strange error. Here is a small example where I am importing the "HelpBlock" component. import PropTypes from 'prop-types'; import React from 'react'; i ...

Is it possible to simultaneously execute an animate and a fade out effect?

Is there a way to simultaneously move "app1" to the left and fade it out? Currently, the functions are executing one after the other. I want them to occur simultaneously, without the left movement happening before the fade out. Thank you! <!DOCTYPE h ...

Search for the location where the code is not functioning as intended

Take a look at this HTML code snippet: <input value="9961" name="c_id" id="c_id" type="hidden"> <input name="user_id" id="user_id" value="1" type="hidden"> <textarea id="comments" name="comments" style="width: 310px; resize: none; height: 7 ...

Error occurs when the asynchronous function is invoked and completes, or when the callback is not a valid function when called on the

Attempting to create a function that calls other functions: copy = () => { copyHtml(); copyCss(); copyJs(); copyImg(); } exports.copy = copy; When using gulp copy, the function runs but an error is encountered: The following tasks did ...