Create a D3 Simple Line Graph using an Array

Attempting to utilize the following code: http://bl.ocks.org/3883245, but instead of loading a TSV file, I am loading the data from an array. Here is what the array looks like:

[["2012-10-02",2],["2012-10-09", 2], ["2012-10-12", 2]]

Then, I applied this function on it to get CSV Format:

var data = d3.csv.format(BigWordsDates2[ArrayIndex]);

However, nothing is displaying.

Below is the complete code: I believe I am close to making it work, but after working on it for three days, I still can't seem to get it right:

var margin = {top: 20, right: 20, bottom: 30, left: 50},
        width = 80 - margin.left - margin.right,
        height = 80 - margin.top - margin.bottom;

        var data = d3.csv.format(BigWordsDates2[ArrayIndex]);

        var parseDate = d3.time.format("%Y-%b-%d").parse;

        var x = d3.time.scale()
            .range([0, width]);

        var y = d3.scale.linear()
            .range([height, 0]);

        var xAxis = d3.svg.axis()
            .scale(x)
            .orient("bottom");

        var yAxis = d3.svg.axis()
            .scale(y)
            .orient("left");

        var line = d3.svg.line()
            .x(function(d) { return x(d.date); })
            .y(function(d) { return y(d.close); });

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

        d3.csv.parseRows(data, function(data) {
          data.forEach(function(d) {
            d.date = parseDate(d.date);
            d.close = parseInt(d.close);
          });

         x.domain(d3.extent(data, function(d) { return d.date; }));
         y.domain(d3.extent(data, function(d) { return d.close; }));

          svg.append("g")
              .attr("class", "x axis")
              .attr("transform", "translate(0," + height + ")")
              .call(xAxis);

          svg.append("g")
              .attr("class", "y axis")
              .call(yAxis)
            .append("text")
              .attr("transform", "rotate(-90)")
              .attr("y", 6)
              .attr("dy", ".71em")
              .style("text-anchor", "end")
              .text("Price ($)");

          svg.append("path")
              .datum(data)
              .attr("class", "line")
              .attr("d", line);
        });`

I suspect that there might be an issue with the d.date and d.close, but I haven't been able to pinpoint it yet.

Answer №1

The data in the chart is structured as follows:

[{ date: '...', close: '...'},
 { date: '...', close: '...'}]

To utilize this format, you will need to parse your array like so:

// Adjust your data parser
var parseDate = d3.time.format("%Y-%m-%d").parse;

var arrData = [
  ["2012-10-02",200],
  ["2012-10-09", 300], 
  ["2012-10-12", 150]];

// Transform the array into the desired format
var data = arrData.map(function(d) {
    return {
      date: parseDate(d[0]),
      close: d[1]
    };
});

For a functional example, visit: http://jsfiddle.net/jaimem/T546B/

Note: Depending on your data, adjustments to your y scale's domain may be necessary.

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

jQuery is not defined when importing reactjs, bootstrap, and npm modules

Having trouble using Bootstrap in my React app, as I keep getting an error message saying Error: Bootstrap's JavaScript requires jQuery. I've already imported jQuery and tried various solutions found in other posts like: import $ from 'jque ...

The JQuery .replaceWith method exclusively offers unprocessed HTML content

I'm experiencing a minor issue with my ajax response where it returns raw html and does not execute any scripts, resulting in the jquery ui scripts not being executed. Here are some details: I am currently working with ASP.NET MVC and I need to comm ...

Having trouble with ui-router: "$injector:modulerr" - it seems an error has occurred

I recently started the tutorial AngularJS Tutorial: Learn to Build Modern Web Apps with Angular and Rails by Thinkster, but encountered a problem. After creating an inline template, I ended up with a blank page and an error message $injector:modulerr with ...

Prevent Purchase Button & Implement Modal on Store Page if Minimum Requirement is not Achieved

On my woocommerce shop page, I am facing an issue where all items are added to the mini-cart without meeting the minimum order requirement. This results in users being able to proceed to checkout without adding enough items to meet the minimum order amount ...

The process of comparing two arrays of objects in es6 and filtering out the unmatched arrays

In my Angular application, I'm attempting to retrieve only the updated array that was modified from the user interface. Within this scenario, I have two arrays in which one of the role names has been changed. My goal is to compare and extract the mod ...

Chosen preference stored in local storage

I am working on a feature where the selected option needs to be stored in local storage. I have another select component that tracks the data received from GraphQl and adds it to local storage after converting it. However, I am facing an issue with imple ...

Ways to retrieve the bounding rectangle of an element PRIOR to applying a transformation?

Is there a way to obtain the dimensions and position of an element using Element.getBoundingClientRect(), but without taking into consideration any transformations applied through the CSS property transform? I am looking for a method that provides the rect ...

If the visitor navigated from a different page within the site, then take one course of action; otherwise

How can I achieve the following scenario: There are two pages on a website; Parent page and Inside page. If a user navigates directly to the Inside page by entering the URL or clicking a link from a page other than the Parent page, display "foo". However, ...

What is the most efficient way to organize an array by date?

Here is the data I have: const data = [{date: "2022-05-10 13:36:00", open: 155.535, low: 155.4, high: 155.67, close: 155.44}, {date: "2022-05-10 13:35:00", open: 155.23, low: 155.2102, high: 155.62, close: 155.53}, {date: "2022-05 ...

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 ...

Is it feasible to customize the appearance of native scrollbars in GWT without the need for custom scrollbar definitions or the use of ScrollPanel or CustomScrollPanel?

After encountering an issue with a page jumping due to the appearance of a vertical scroll bar, I have decided to always display the scroll bar by applying html { overflow-y: scroll !important; }, instead of using a script to monitor and adjust window/docu ...

Experiencing a scroll problem in the latest version of Google Chrome for Android while using ReactJS? The issue seems to have migrated from the earlier version 99.xxxxxx to

Previously, my website was functioning perfectly in full screen mode. However, after updating Chrome on Android to the latest version (116.xxxxxx....), I noticed that it is now displaying a scrolling behavior that was not present in the earlier version (99 ...

What specific method of sorting does this code utilize?

Here's a JavaScript code snippet that sorts an array of n numbers in ascending order. I've used this code in several interviews, but I'm still unsure about which sorting algorithm it represents. let arr = [7, 9, 2, 11, 5] for (let i = 0; i ...

Could you please advise on how to use three.js to render Uint8ClampedArray image data?

program-image I am developing a web-based Remote Desktop Protocol (RDP) using Windows. My goal is to stream ImageData (Uint8ClampedArray) to the browser in real-time (every 100ms), and I have achieved this by utilizing server-side rendering with node-can ...

What is the best way to display data from multiple lists that are returned by a JSON function?

List of My Models: ClassAllocate: Contains Id, DepartmentId, CourseId, RoomId, DayId, StartTime, EndTime Course: Consists of Id, CourseCode, CourseName, DepartmentId Room: Includes Id, RoomNumber Day: Has Id and DayName My goal is to search for course ...

What is the method for verifying a password in the login process when it has been hashed by bcrypt during registration?

Currently in the process of developing a signup and login page using Node.js with Pug, Mongoose, and bcrypt. I am encrypting and storing passwords in the database after registration or sign up. I'm facing an issue with the comparison function as it r ...

Moving information from two modules to the service (Angular 2)

Recently in my Angular2 project, I created two components (users.component and tasks.component) that need to pass data to a service for processing before sending it to the parent component. Code snippet from users.component.ts: Import { Component } fro ...

What is the best way to retrieve the value of a checked radio button in React.js?

I am in the process of creating a well-structured to-do list and I want to be able to add the input from any selected radio button into one of three options arrays (the array is not included in the code, but rather in a parent component). I am looking fo ...

Shopping cart feature in PHP - Ajax response only functioning once

I'm in the process of developing a shopping cart. I start by adding products to the cart, then use Ajax to dynamically update the quantity when it changes. Everything works smoothly after the first change, but subsequent quantity updates do not refres ...

service is not allocated to the designated port in the hosting.json file

Take a look at my Program.cs public class Program { public static void Main(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("hostin ...