Troubleshooting D3 grouped bar chart grid alignment and resolving console errors

I've been working on a grouped bar chart using D3, but I'm encountering some issues with the display of the bars. Despite my efforts to troubleshoot, I can't seem to pinpoint the exact cause of this problem. The code snippet provided below should give you an idea of what I've implemented so far.

var margin = {
    top: 20,
    right: 30,
    bottom: 30,
    left: 40
  },
  width = 960 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var z = d3.scale.category20c();

var svg = d3.select("body").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 + ")");

var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ");

var data = [{
  "data": [
    [
      "2016-01-21T01:20:00.000Z",
      1.41818181818182
    ],
    [
      "2016-01-21T02:28:00.000Z",
      1.90661764705882
    ],
    [
      "2016-01-21T03:36:00.000Z",
      1.66764705882353
    ],
    [
      "2016-01-21T04:44:00.000Z",
      1.51691176470588
    ],
    [
      "2016-01-21T05:52:00.000Z",
      1.40955882352941
    ],
    [
      "2016-01-21T07:00:00.000Z",
      1.46323529411765
    ],
    [
      "2016-01-21T08:08:00.000Z",
      1.48308823529412
    ],
    [
      "2016-01-21T09:16:00.000Z",
      1.89384615384615
    ]
  ],
  "label": "a"
}, {
  "data": [
    [
      "2016-01-21T01:20:00.000Z",
      4.98701298701299
    ],
    [
      "2016-01-21T02:28:00.000Z",
      5.0
    ],
    [
      "2016-01-21T03:36:00.000Z",
      4.94852941176471
    ],
    [
      "2016-01-21T04:44:00.000Z",
      4.91176470588235
    ],
    [
      "2016-01-21T05:52:00.000Z",
      4.81617647058824
    ],
    [
      "2016-01-21T07:00:00.000Z",
      5.0
    ],
    [
      "2016-01-21T08:08:00.000Z",
      4.94117647058824
    ],
    [
      "2016-01-21T09:16:00.000Z",
      4.96969696969697
    ]
  ],
  "label": "b"
}];


... // The rest of the code structure remains unchanged

text.inner-circle {
  font-weight: 400;
  font-size: 12px;
  text-transform: uppercase;
}
text.inner-text {
  font-weight: 400;
  font-size: 36px;
  font-family: 'Metric Regular', 'Metric';
  text-align: center;
  font-style: normal;
  text-transform: uppercase;
}
path {
  stroke: steelblue;
  stroke-width: 2;
  fill: none;
}
.axis path,
.axis line {
  fill: none;
  stroke: grey;
  stroke-width: 2;
  shape-rendering: crispEdges;
}
.grid .tick {
  stroke: lightgrey;
  stroke-opacity: 0.7;
  shape-rendering: crispEdges;
}
.grid path {
  stroke-width: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

I would greatly appreciate any assistance in identifying the root cause of this issue. Plnkr.co

Answer №1

Successfully displayed your grid.

y.domain([0, d3.max(d3.merge(ary), function(d) {
  console.log(d.y0 + d.y); //This is NaN = Not a number
  //return d.y0 + d.y;
  return d[1]; //returns grid lines if that is what you want
})]);

Let's address the following part of your script:

layer.selectAll("rect")
  .data(function(d) {
    return d.data;
  })
  .enter().append("rect")
  .attr("x", function(d) {
    return x(parseDate.parse(d[0]));
  })
  .attr("y", function(d) {
    console.log(d[1]);
    return y(d[1]); //Note this is returning data
  })
  .attr("height", function(d) {
    return y(d[1]); //Note this is returning data
  })
  .attr("width", x.rangeBand() - 1);

By implementing the above changes to your code, I can see the rectangles without any errors. However, there are some CSS adjustments needed as the bars are not aligned properly with the x-axis. Additionally, you need to include more code for grouping your data effectively.

You may refer to this example of a grouped bar chart for guidance. Upon examining this illustration, it appears that you have a way to differentiate between x0 and x1 (first and second groups). Incorporate this distinction into your code to proceed with creating the next set of rectangles.

Answer №2

Those two errors popping up are as follows:

Error: Invalid value for <rect> attribute y="NaN"
Error: Invalid value for <rect> attribute height="NaN"

Essentially, this is indicating that there's some incorrect math going on (NaN = not a number).

The problematic part of the code looks like this:

.attr("y", function(d) {
  return y(d.y + d.y0);
})
.attr("height", function(d) {
  return y(d.y0) - y(d.y + d.y0);
})

What's the issue? Well, by inserting some console.log() statements into those functions, you'll quickly notice that the attributes you're trying to access are missing.

If you examine the code just before the troublesome calculations:

.data(function(d) {
  return d.data;
})

You've applied a key function to the

d3.selection.data(\[values\[, key\]\])
method, but you haven't actually supplied any relevant data (well, at least none that matters in this context; technically, the function definition itself serves as a data object, which is why no error is raised).

Here's what you should have done:

.data(data) // or maybe you meant .data(ary)

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

[Vue alert]: Issue with rendering: "TypeError: Unable to access property 'replace' of an undefined value"

I'm currently working on a project similar to HackerNews and encountering the following issue: vue.esm.js?efeb:591 [Vue warn]: Error in render: "TypeError: Cannot read property 'replace' of undefined" found in ---> <Item ...

Is the speed of JavaScript procedures stored in MongoDB faster than other databases?

I am curious about the implications of storing JavaScript procedures. Having come across the Blog Entry by PointBeing, I find myself with some inquiries. Are there benefits to saving my code in the database? Specifically functions like document lookups ...

"Unable to locate the specified file or directory" error message pops up while attempting to save a file

Currently, I am in the process of generating a JSON file using my website with intentions to deploy it later. Below is the code snippet that I have implemented: saveFile = (i, data) => { var filename = `${i}_may.json`; var folder_list = ["desktop", ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

Upcoming challenge regarding naming files

I came across a new problem: Error: ENOENT: file or directory not found, rename '/home/user/my-web/.next/export/en/cities/berlin.html' -> '/home/user/my-web/.next/server/pages/en/cities/berlin.html' What could be causing this issu ...

Sending a C# variable to an HTML file

I’m struggling to understand how I can use jQuery to access a variable from C# named sqlReq. My main objective is to be able to input my own SQL data into a PieChart. However, I’m unsure about how to call and define C# SQL requests in HTML or jQuery. ...

Solving the error message: "Objects cannot be used as a React child (found: object with keys {})"

I am currently in the process of developing a full stack website that utilizes React, Express, Sequelize, and mySQL. The site is operational with features like registration and login implemented successfully. However, I encountered an issue when trying to ...

Retrieve specific information from a nested JSON structure and combine it into a unified array

I am struggling to extract specific data from the JSON below and add them to a single array. I have managed to extract all the text values inside the block, but I am facing difficulty in pushing it to a single array. The code snippet I used for extraction ...

Methods for sending an indexed array object back to a getJSON request with jquery

When sending an Indexed Array to a PhP file on the server side using getJSON, it seems like using an associated array may be a better choice. However, the indexed array works fine and the data is successfully received on the server. I am able to process th ...

Tips for moving an element to the end of an array

Patients' data is stored in the MongoDB database, and all patients are mapped through on the frontend to display a list. An additional boolean value indicates whether a patient is archived or not. If a patient is archived, it should be displayed at th ...

Tips for sending a Json array to a servlet

[DUPICATE] Here is the JSON code I am using for my POST request: var data_create = JSON.stringify($("#form_create_delegate").serializeArray()); alert("data_create content" + data_create); // console.log(data_create) $.ajax({ ...

Is it possible to have a text box that is partially read-only and partially editable?

<form> <div class="col-sm-2" style="margin-top: 5px;color:#357EBD;font-weight:bold;" id="sub-ticketid"><?php echo 'Ticket 12345#'; ?></div> <input type="text" class="form-control" style="background:#fff;" name="sub-hold ...

Can you share the updated class name for indicating errors in input groups in Bootstrap 4?

I am currently working on creating a form. I want to implement a feature where incorrect data entered will be highlighted in red, and correct data entered will be highlighted in green. This is the code snippet from my .js file: function checkForm() { v ...

Angular - Issue: Unable to locate 'classlist.js'

require('classlist.js'); While building the project using Angular CLI, an error appeared in the console. I ran the command "npm install --save classlist.js" within the project directory. Error: Module not found: Can't resolve 'classl ...

In Typescript, it is possible to assign properties to an object that are not explicitly defined in the object's type definition

I'm confused as to why Typescript isn't flagging this as an error... When I conditionally add a new property to an object that doesn't exist in the type definition, Typescript still allows it type Filters = { keywords: Array<stri ...

Issue with dynamically adjusting flex box width using JavaScript

Currently, I am developing a user interface that heavily relies on flexbox. The layout consists of a content area and a sidebar that can be toggled by adding or removing a specific class. Whenever the sidebar is toggled, the content area needs to be manua ...

Using Angular 2 to assign a pipe dynamically from a variable

Could something like the following be achievable: {{property | some_variable_name}} I am aiming to utilize a pipe that is defined in a JSON configuration (or variable), but I am uncertain if it is feasible to include the pipe name within the interpolatio ...

What is the best way to store the dom in cache to ensure that the page remains unchanged when navigating back using the back button?

When adding models to my JavaScript application's model collection using AJAX calls, I encounter an issue where if I click on a model and go to the next page, all the loaded models disappear when I hit the back button. What is the most effective way t ...

Troubleshooting CORS Problem in VUE JS 3 while Making API Request from Localhost to External API服务

I've been dealing with a CORS issue for quite some time now. I've tried all the solutions on Stack Overflow, but nothing seems to be working for me. Can anyone help me figure out what's wrong with my code? I'm using VUE JS 3 and trying ...

Disabling animations in Reactjs with CSSTransition and Group Transition

Currently, I am experimenting with REACTJS to build a basic app featuring Transitions. In my project file, I have imported CSSTransitions and Group Transition. However, when attempting to implement CSSTransition for specific news items, the animations are ...