I am experiencing difficulty in retrieving the result for the following code snippet

I'm currently attempting to retrieve data for my chart from a data.csv file.


        <!DOCTYPE html>
        <html>
        <head>
        <title>D3 test</title>
          <style>
            .grid .tick {
              stroke: lightgrey;
              opacity: 0.7;
            }
            .grid path {
              stroke-width: 0;
            }
            .chart {
            }
            .main text {
              font: 10px sans-serif;
            }
            .axis line, .axis path {
              shape-rendering: crispEdges;
              stroke: black;
              fill: none;
            }
            circle {
              fill: steelblue;
            }
          </style>
          <script type="text/javascript" src="http://mbostock.github.com/d3/d3.v2.js"></script>
          <script src="http://d3js.org/d3.v3.min.js"></script>
          <script src="http://d3js.org/topojson.v1.min.js"></script>
        </head>
        <body>
          <div class='content'>
            <!-- /the chart goes here -->
          </div>
          <script type="text/javascript" src="scatterchart.js"></script>
        </body>
        </html>
    

Here's the code snippet from scatterchart.js:


        var data = []
        d3.csv("data.csv", function(csvData) {
            data = csvData.forEach(function(d) { return [+d.first, +d.second]; });
            console.log(data);

            var color = d3.scale.ordinal().range(["#b41f2d", "#ff7f0e"]);

            // Rest of the script continues here...
    

And the data.csv file contains:


        first,second
        2,2
        3,3
        4,4
        5,4
        5.5,5
        6,6
        6,7
        6.5,8
        6.5,16
        17,16
    

The error messages appearing in the console window are:

[undefined scatterchart.js:6]

[TypeError: n is undefined d3.v3.min.js:3]

If you have any suggestions on how to resolve these errors and get the desired output, please let me know. Thank you!

Answer №1

The problem lies within the forEach loop. It appears that the usage may not be entirely correct. Here is a suggestion to correct it:

csvData.forEach(function (d,i) {
    data[i] = {
      first: +d.first, 
      second: +d.second
    } 
});

By following this approach, you are creating an array of objects instead of an array of arrays with 2 elements as in your original code.

If you prefer, you can also replace d[0] and d[1] with d.first and d.second. It's a matter of personal preference. Using dot notation can often make the code clearer, but there are situations where bracket notation is required.

Furthermore, it's important to consistently use the variable name data instead of csvData throughout your code.

You can view a functional demo 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

Is there a way to verify if a user has selected the correct answer in a quiz program?

Here we have code segments in ajax, javascript, html, and an xml file. I'm looking to calculate the total score based on user input to determine if they selected the correct answers for a test. I've attempted to figure this out, but I'm str ...

Having difficulty in selecting the element

My current challenge involves using Appium to automate a framework I've created. After inspecting an element with Appium inspector, I'm attempting to click on the element within the DOM, even though it's not visible on the device screen. I t ...

When quickly typing, the input formatting using a computed property in Vue.js is not getting applied

Is there a way to format data in the following manner: m:ss, while restricting the input textbox to display only 3 characters or fewer? (m = minute, s = seconds) The code snippet below successfully formats the data in m:ss format. However, when entering m ...

Adding an additional border when combining two divs with rounded borders

I attempted to create a design similar to the Instagram "ask me a question" box, but I am encountering an issue where there is some extra border around the title when the two divs merge. What am I doing incorrectly? .info { overflow: hidden; ...

Utilizing Angular 5: Enhancing ngFor with a Pipe and a Click Event

Iterating through an array of objects using *ngFor, I apply various filters via pipes to manipulate the resulting list. One of these pipes relies on a user input from a search field. Upon clicking on one of the ngFor elements, the corresponding object is p ...

The content of the string within the .ts file sourced from an external JSON document

I'm feeling a bit disoriented about this topic. Is it feasible to insert a string from an external JSON file into the .ts file? I aim to display the URLs of each item in an IONIC InAppBrowser. For this reason, I intend to generate a variable with a sp ...

Converting string literals to an array of enums

I have a scenario where I am getting the following data in an API response: { "roles": [ "ADMIN", "USER" ] } The response always includes an array of roles (USER, PRESENTER, ORGANIZER, and ADMIN). I am looking to transform this into a valid TypeScript a ...

Is it true that Redux Saga's select function returns mutable state?

Is the state returned by Redux Saga's select function mutable or immutable? To learn more, visit https://github.com/redux-saga/redux-saga ...

Recording audio using Cordova and Javascript

Recently, I've been dabbling in creating a new app using Cordova, VueJs, and Onsen UI for VueJs. One of the main features I want to implement is the ability to use the microphone on Android or iOS devices to record audio and then send it to the Google ...

The $(document).ready function may not be compatible with Internet Explorer

I have a page with two links - one for registering and one for logging in. Currently, the register link is the most important. When clicked, it loads a .tpl file using jQuery's load function. Within this tpl file, I include a new JavaScript file usin ...

Navigating a local and server environment with relative paths in a web server's multiple sites

My ASP.NET website is published to a web server with multiple sites, such as www.example.com/SiteA or www.example.com/SiteB. Before publishing, I test the site locally at localhost:12345. When referencing an image path like /Images/exampleImage.gif, it wo ...

Is there a way to maintain the vertical alignment of spans within an HTML div after numerous drag and drop operations have taken place?

Recently, I created a JavaScript program (code provided below) to enable the dragging and dropping of <span> elements containing Greek characters within a basic <div> container. Upon initial page load, everything appears perfectly aligned vert ...

Stable placement in browsers using webkit technology

Having trouble with fixed positioning on webkit browsers. Works fine in Firefox, but can't seem to solve the issue. You can see the problem here: When clicking on a project, a page is loaded using jQuery's .load() function. On this page, there ...

Enhancing User Experience with Load Indicator during State Changes in React Native

I'm facing an issue where the page for displaying a single item is loading slowly - I need to delay the page from loading until the object has changed. After checking the navigation params through console log, I can see that the id changes when each b ...

Is it necessary for Webpack to process the index.html file for Vue applications?

I am facing an issue with my index.html file where the assets inside the head tag are not loading as images but as the index.html file itself. I have included the following links in my head tag: <link rel="apple-touch-icon" sizes="60x60" href="./assets ...

What is the limit on the amount of input data (in CSV or JSON format) that can be used to create a

Attempting to visualize a large dataset using D3.js has posed a challenge for me. The data size is 261 MB with approximately 400,000 rows in CSV format. Even when I attempt to run it with just 100,000 rows, the visualization does not appear on the browser. ...

Display the div according to the $index selected from the AngularJS list

Below is the structure of my HTML code: <div class="col-md-4"> <ul class="list-group text-left"> <a href="#" class="list-group-item" ng-click="showData($index)" ng-repeat="field in Data"> {{ field.name }}</a> ...

The curly braces in AngularJS are not resolving as expected, however, the ng-bind directive is functioning properly

I'm currently working on a Django application and utilizing AngularJS for my frontend. I have a straightforward piece of code that looks like this: <div class="vert-carousel" ng-controller="PrizeController"> <div class="gallery-cell" n ...

AngularJS Multiple Select fails to display preselected options

This morning, I dedicated a significant amount of time to finding a solution for assigning multiple values to an entity on my form. The scenario is as follows: I have an Entity named QualityData that can have various MechanismIdentifiers. After brainstor ...

`Discover the latest version of Tailwind using JavaScript or PHP`

My setup includes Laravel v8.81.0 (PHP v8.1.2), Vue v3.2.30, and Tailwind https://i.sstatic.net/fVbJB.png I am looking to fetch the Tailwind version in JavaScript similar to how I can get the Vue version using: //app.js require('./bootstrap'); ...