Error encountered in D3 while processing data file

I am currently working on my graduation project in computation, and I am facing an issue with D3. The code works fine when I pass the data directly to it, but when I try to use data from a file, it gives me an error saying "n does not exist." I am unsure why this is happening. Here is the code snippet:

PS: If anyone requires a sample of my data file, please feel free to request it.

Thank you in advance!

<code>
<!DOCTYPE html>
<meta charset="utf-8">
<title>Causa básica</title>
<style>
 .axis path, .axis line
        {
            fill: none;
            stroke: #777;
            shape-rendering: crispEdges;
        }

        .axis text
        {
            font-family: 'Arial';
            font-size: 13px;
        }
        .tick
        {
            stroke-dasharray: 1, 2;
        }
        .bar
        {
            fill: FireBrick;
        }
</style>
<svg id="visualisation" width="1000" height="500"></svg>
<script src="http://d3js.org/d3.v3.min.js"></script>

<script>
InitChart();

function InitChart() {
/*
  var lineData = [{ 
    'x': 1, 
    'y': 1.0807955e-01
  }, {
    'x': 2,
    'y': 1.2815365e-01
  }, {
    'x': 3,
    'y': 9.3269178e-02
  }, {
    'x': 4,
    'y': 9.3894191e-02
  }];*/

var lineData;
        d3.tsv("data.tsv", function(data) {
        lineData=data 
        });

  var vis = d3.select("#visualisation"),
    WIDTH = 1000,
    HEIGHT = 500,
    MARGINS = {
      top: 20,
      right: 20,
      bottom: 20,
      left: 50
    },
    xRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(lineData, function (d) {
        return d.x;
      }),
      d3.max(lineData, function (d) {
        return d.x;
      })
    ]),
    yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(lineData, function (d) {
        return d.y;
      }),
      d3.max(lineData, function (d) {
        return d.y;
      })
    ]),

    xAxis = d3.svg.axis()
      .scale(xRange)
      .tickSize(5)
      .tickSubdivide(true),

    yAxis = d3.svg.axis()
      .scale(yRange)
      .tickSize(5)
      .orient("left")
      .tickSubdivide(true);


  vis.append("svg:g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
    .call(xAxis);

  vis.append("svg:g")
    .attr("class", "y axis")
    .attr("transform", "translate(" + (MARGINS.left) + ",0)")
    .call(yAxis);

  var lineFunc = d3.svg.line()
  .x(function (d) {
    return xRange(d.x);
  })
  .y(function (d) {
    return yRange(d.y);
  })
  .interpolate('basis');

vis.append("svg:path")
  .attr("d", lineFunc(lineData))
  .attr("stroke", "blue")
  .attr("stroke-width", 2)
  .attr("fill", "none");

}

</script>
</code>

Answer №1

Issue with Asynchronous Function Execution.

The specified function:

    d3.tsv("data.tsv", function(data) {
        lineData=data //assigned data, but facing issues
    });

gets executed after the rest of the code has run.

To resolve this, consider moving all the code inside the function and placing it after lineData=data;. Alternatively, create a separate function:

var lineData;
d3.tsv("data.tsv", function(data) {
     visualizeData(data); 
});
function visualizeData(lineData) {
  var vis = d3.select("#visualisation"),
  WIDTH = 1000,
  HEIGHT = 500,
  MARGINS = {
    top: 20,
    right: 20,
    bottom: 20,
    left: 50
  },
  // additional code here
}

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

Retrieving live comments from YouTube streams for a customized React application

Currently working on developing a React Webapp to organize and showcase superchats during a live stream. My initial attempt involved utilizing the YouTube LiveChat API, but I hit a roadblock as it requires authentication from the live stream owner, which ...

Adjust text dynamically using PHP

Hello everyone, I am currently working on a form where I would like to have a text displayed and calculate the price when a user selects an option from two dropdown menus. The first dropdown menu includes: <select id="recipient" name="recipient" tabin ...

Guide to dynamically adding a class in VueJS based on a certain condition

I'm in the process of transitioning a project to Vue, and I'm curious about how I can dynamically assign classes to specific elements based on database values rendered with Vue. Previously, I had this code set up without Vue: $(document).ready(f ...

Issues with the directory for Chrome

Currently, I am utilizing jQuery and running an HTML file on my local machine without a server. Interestingly, the code works perfectly fine on Firefox but encounters issues on Chrome: $('#result').load('test.html'); It appears that t ...

Javascript redirection not functioning correctly

Currently, I am working with PHP Codeigniter. The current URL of my page is => http://localhost.hbs.com/hbs/merchant/login I want to redirect my page to => http://localhost.hbs.com/hbs/category when a specific event occurs. I have attempted to achie ...

What is the total count of different types of objects present in the array?

... let stock = [ { candy: "Twix", available: 150, weeklyAverage: 200 }, { candy: "Kit Kat", available: 80, weeklyAverage: 100 }, { candy: "Skittles", available: 250, weeklyAverage: 170 }, { candy: "Reese's P ...

Loop through an array using a Meteor template

js if (Meteor.isClient) { Template.body.helpers({ fixtures: function () { Meteor.call("checkTwitter", function(error, results) { return results.data.fixtures; }); } }); } if (Meteor.isServer) { Meteor.startup(function ...

Rendering a child component beyond the confines of its parent component in React.js: A Step-by-Step Guide

I am working with a table component that has sticky headers and dropdowns, ellipsis menus, and other complex components within the table body rows. Each row of the table contains nested table body rows, and the parent rows stick to their child rows. Howeve ...

Connect the scroll wheel and then proceed to scroll in the usual way

There are two div elements with a height and width of 100%. One has the CSS property top:0px, while the other has top 100%. I have implemented an animation that triggers when the mousewheel is used to scroll from one div to the other. The animation functi ...

New Update Required for Selenium Chrome Driver Version in ASP.NET Core Selenium Testing

Currently, I am encountering challenges with my Selenium tests failing both locally and on the DevOps Azure pipeline for Selenium testing. The root of the error seems to be a version discrepancy between the browser and driver being utilized. Despite atte ...

The error message "GraphQL non-nullable field returned null" appears to indicate that a non-nullable

Embarking on my journey to create a GraphQL server for the first time, here's what I've got so far. Check out my progress on GitHub An error keeps appearing in GraphQL when attempting to filter users by username. View the GraphQL error here T ...

C++ skipping the first line of data file - why is this happening?

There seems to be an issue with the loop in my school assignment. It's skipping the first line of the data file I'm using as input. Here is the sample data from the file: Joe Johnson 89 Susie Caldwell 67 Matt Baker 100 Alex Anderson 87 Perry D ...

What is the process for importing fresh components from node_modules into the project?

Help! I've been using Webpack and WordPress for a while, but recently decided to dive into Vue.js. The problem is, I'm completely lost. I managed to integrate Vue with WordPress and Webpack after 5 days of work, but I still don't understand ...

Stop the form validation from executing on an AngularJS webpage

I have set up a basic login form for my web application where users can enter their username and password. I've incorporated the standard angularjs validation to ensure that the inputs are filled out correctly. However, I am encountering an issue whe ...

What is the best way to change the CSS of a particular element within the #shadow-root (open)?

Can you help me modify the display of the p element inside the SR element with the #one id using CSS? #one ?SHADOW-ROOT-QUERY-SELECTOR? p { display: none}; <div> <p>My Website</p> <div id="one"> <!--#shadow-root (o ...

Using references to pass variables in TypeScript [Angular 8]

I have several variables within the html of this component that are assigned their values by the typescript file. The declaration in the html is as follows: <h1>{{myproperty1}}<\h1> <h1>{{myproperty2}}<\h1> <h1>{{myp ...

Invoke a JavaScript function once the div has finished loading

After clicking on a radio button, I am dynamically loading a div element. I want to hide a specific part of the div once it is loaded. $(function($) { $('.div_element').on('load', function() { $('.textbox').hide(); } ...

What steps should I follow to include a message in the custom form validation rule in my React application?

I'm currently developing a chat application using React 18 and Firebase 9. For cleaner form validation, I have integrated the Simple Body Validator. Within the Register form, there's an input field of type file for uploading user avatars. The ...

A guide on expanding an HTML table dynamically with MVC razor syntax

My goal is to dynamically add new rows to a table by following the advice given in this answer on Stack Overflow: Add table row in jQuery I have successfully implemented it for one of my table requirements as seen below: function onAddItem() { $( ...

Changing the value of a JavaScript local variable with each function invocation

Is it possible to increment the value of i each time myFunction() is called? Currently, i is always initialized to 0, resulting in zero as the output. How can we ensure that i remains a local variable and gets properly incremented? Can this be achieved u ...