The issue arises when d3.scaleLinear returns NaN upon the second invocation

My journey with d3.js is just beginning and I'm taking it slow. Currently, I'm focused on creating a bar chart where data is loaded from a json file. When I click on the bars, the data changes to another column in the json.

This is how my json file looks:

[
  {
    "ym": "201801",
    "clients": 179,
    "trans": 987,
  },
  {
    "ym": "201802",
    "clients": 178,
    "trans": 334,
  }
]

Initially, everything works fine when the page loads - the chart displays properly and functions well. However, upon clicking the bars, I encounter issues where the axis change, text updates but the bars disappear. The console error message reads:

d3.v4.min.js:2 Error: <rect> attribute y: Expected length, "NaN".
(anonymous) @ d3.v4.min.js:2
d3.v4.min.js:2 Error: <rect> attribute height: Expected length, "NaN".

I tried debugging by checking if the data type was causing this problem (as per another thread's suggestion), but couldn't find any discrepancies there. The main idea behind my two related functions is simple - clicking the bars should only alter their color, but somehow they disappear instead of changing color.

Here's an excerpt from the function that handles this behavior:

function alter_show() {

d3.json("testV.json", function(data) {

var y = d3.scaleLinear().range([height,1]);
var x = d3.scaleBand().rangeRound([0, width]);

y.domain([1,d3.max(data,function(d) {return d.clients})]);
x.domain(data.map(function(d) {return d.ym}));

svg.select(".x.axis").call(d3.axisBottom(x))
svg.select(".y.axis").call(d3.axisLeft(y))


bar = svg.selectAll("rect")         

bar.data(data).enter().append("rect")
    .attr('class','bar')
    .attr("x", function (d) {return x(d.ym); })
    .attr("y", function (d) {return y(d.clients); })
    .attr("height", function (d) {return height - y(d.clients)})
    .attr("width", x.bandwidth()*0.5)
    .attr("color","black")
    .attr("transform",
      "translate(" + (margin.left + x.bandwidth()*0.25) + "," + margin.top + ")")
    // Event Listeners for bar interaction
    .on('mouseenter', function() {
        d3.select(this).transition().duration(100).attr('opacity',0.5).attr('color', 'orange')})
    .on('mouseleave', function() {
        d3.select(this).transition().duration(100).attr('opacity',1)})
    .on('click',alter_show);


// Displaying additional values inside bars
svg.append("g").selectAll("text").data(data).enter().append("text")
    .attr('class','value')
    .attr("x", function (d) {return x(d.ym); })
    .attr("y", function (d) {return y(d.trans); })
    .text(function (d) {return d.trans})
    .attr('font-size','0.7em')
    .attr("transform",
      "translate(" + (margin.left + x.bandwidth()*0.25)  + "," + (margin.top + 30) + ")");

// Updating existing bars with transitions based on new data:
bar.exit().remove();
bar.transition()
    .duration(750)
    .attr("y", function(d) {
      return y(d.value);
    })
    .attr("height", function(d) {
      return height - y(d.value);
    })});}

In conclusion, the function performs as expected upon page load, but faces issues with bar display post-click. Any insights or additional information would be greatly appreciated. Thank you for your help!

Answer №1

Can you locate the attribute value in your dataset?

bar.transition()
    .duration(750)
    .attr("y", function(d) { return y(d.value); })
    .attr("height", function(d) { return height - y(d.value); });

All other issues with the chart will need to be addressed by you.

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

Generate a fresh array using the information extracted from a JSON file

I need assistance in extracting a new array from JSON data. The desired output should be an array containing "itog" values. [12860498,20156554,19187309] [ { "0": { "itog": 12860498, "return": ...

Having difficulty implementing getJSON function in CodeIgniter framework

My goal is to integrate AJAX calls into my website using codeigniter in order to receive live updates from the database. The click button function properly and displays all JSON data, however, I am facing an issue when trying to display a specific array a ...

You can see the JavaScript code directly in the browser

I'm completely puzzled as to why this is happening. How strange that the JavaScript code is visible on the browser, almost appearing like regular text on the web page. This mysterious occurrence seems to be exclusive to Firefox. Despite scouring vario ...

Solving the Issue of Multiple Object Handling in JavaScript

Is there a way to remove the object from a JSON response and only keep the array of objects? I've tried using methods like Slice, Replace, and Filter but haven't been successful. {"error":"no data"}[{"name":"Ali"},{"name":"Momin"}] What I need ...

Displaying HTML content using Typescript

As a newcomer to typescript, I have a question regarding displaying HTML using typescript. Below is the HTML code snippet: <div itemprop="copy-paste-block"> <ul> <li><span style="font-size:11pt;"><span style="font-family ...

"Enhance your web development with Vue.js and Vue-chart.js for beautiful linear

I'm currently struggling to implement a linear gradient background on my Vue-chart.js line chart. Despite searching high and low, the documentation and examples available are not proving to be helpful. After importing the Line component from vue-char ...

Issue with my "message.reply" function malfunctioning in Discord.JS

I'm currently learning how to use discord.Js and I am facing an issue with my message.reply function not working as expected. I have set up an event for the bot to listen to messages, and when a message containing "hello" is sent, it should reply with ...

Enter information into the designated text field once you have selected the button

In my PHP/HTML form for user login, I have a password field where users can enter their password or click a button to generate a random one. Although I found some JavaScript code online for this feature, I'm having trouble getting it to work with my ...

Incorporate a local asciinema file into an HTML document

Is there a way to embed a local asciinema session into an html file? Here is how my directory is structured: $ tree . ├── asciinema │ └── demo.cast ├── css │ └── asciinema-player.css ├── index.html ├── js │ ...

the specified computed property does not have a value assigned

Issue with the Computed name Property in a Component <template> <div class="person"> <p>{{name}}</p> </div> </template> <script> export default { name: 'person', data () { return ...

Obtain information stored locally when an internet connection is established

I'm currently facing an issue with my Local Storage data retrieval process in Vuejs while being online. My ToDo app setup consists of Vuejs, Laravel, and MySQL. When the internet connection is available, I store data in localStorage. The ToDo app has ...

Managing the display of numerous ngFor components

If you're interested in learning more about the features I will include, here's a brief overview. I plan to have a project section with cards displayed for each project, all populated from a JSON file. When users click on a card on the website, a ...

Notification for radio button selected

Looking to trigger an alert message when a radio button is not selected? Check out the code below: <form method=post name="spendform" id="spendform"> <input name="price" type="radio" class="invest-coin-check" id="pricemethod" > <button typ ...

Continuously generate new objects every second

I am working on a function that involves adding the RandomBlock object to the scene and then moving it downward on the screen. function enemyPaddleMovement() { scene.add(RandomBlock); RandomBlock.translateX(-8); } The RandomBlock object is created using ...

Updating the handler function for AutoComplete with Checkbox in Material UI using React JS

I am looking to include an <AutoComplete /> field in my form. The options for this field are fetched through a get request, and here is the result displayed in the console. [ { "uid": "c34bb0ed-9f63-4803-8639-a42c7e2a8fb0&q ...

AngularJS error: Uncaught MinError Object

Recently, I started a new AngularJS project and successfully set it up. The installation of angular and angular-resource using bower went smoothly. However, upon installing another service that I have used previously - https://github.com/Fundoo-Solutions/a ...

Pass an image into an input field with the attribute type="filename" using JavaScript directly

My goal is to automate the process of uploading images by passing files directly to an input type="filename" control element using JavaScript. This way, I can avoid manually clicking [browse] and searching for a file in the BROWSE FOR FILES dialog. The re ...

Having trouble aligning my slider in the center

Despite trying various methods to center this slider, such as using align="center" and different margin styles on the images and slider div itself, I am still facing alignment issues. Any assistance would be greatly appreciated. This is my first time posti ...

Is it possible to attach an onclick event to modify a data point in Chart.js?

Currently using chartjs for a small project and facing some challenges with editing data points. Is there a built-in function in this library that allows me to bind an onclick event for displaying a pop-up and removing the point? This is what I am lookin ...

Looking to incorporate ipcRenderer from Electron into your Angular project? Having trouble accessing variables passed from the preload script?

I am struggling with incorporating ipcRenderer into the 'frontend' code of my electron app. Although I found examples in the documentation that use require, this method is not accessible on the frontend side where I am utilizing Angular. In the ...