Creating a visually striking line chart using data from an infotable

I am looking to create a dynamic line chart using d3.js based on data from an infotable. To achieve this, I have converted the information in the infotable into two arrays: a single-dimensional array xValueArray: [0, 10, 20, 30, 40] and a two-dimensional array

yValueArray: [[0, 20, 30, 40, 50], [0, 200, 250, 400, 450]]
. My approach involves mapping the xValueArray to both arrays within yValueArray to represent x and y-coordinates, which I accomplish by using the map function.

    var result = xValueArray.map(function (x, i) { 
        return [x, yValueArray[0][i]];
    });
    console.log(result); //returns [[0,0], [10,20], [20,30], [30,40], [40, 50]]

    var data = result.map(function(d) {
        return {
          x: d[0],
          y: d[1]
        };
    });
    console.log(data); //returns [[x:0, y:0], [x:10, y:20], [x:20, y:30], [x:30, y:40], [x:40, y:50]]

    //************* Plotting of graph ***************   
    var lineFunction = d3.line()
        .x(function(d) {return x(d.x); })
        .y(function(d) {return y(d.y); })
        .curve(d3.curveLinear);

    //plot line
    var path1 = g.append("path")
        .attr("class", "path1")
        .attr("id", "blueLine")
        .attr("d", lineFunction(data))
        .attr("stroke", "blue")
        .attr("stroke-width", 2)
        .attr("fill", "none")
        .attr("clip-path", "url(#clip)");

The line chart is generated successfully, but with only one line as I mapped the first array in yValueArray to xValueArray. To make the chart dynamic, I aim to plot lines corresponding to the number of data fields inputted by the user in the infotable. For example, if there are 2 arrays in yValueArray, I want 2 lines plotted on the chart. How can I accomplish this task? Any guidance or suggestions would be highly appreciated!

Answer №1

Instead of starting with your x array for mapping the y values, switch it up:

const yValuesArray = [
  [0, 20, 30, 40, 50],
  [0, 200, 250, 400, 450]
];

const xValuesArray = [0, 10, 20, 30, 40];

const dataPoints = yValuesArray.map(dataset =>
  dataset.map((value, index) => ({
    x: xValuesArray[index],
    y: value
  }))
);

console.log(dataPoints);

This approach accommodates any number of nested arrays within yValuesArray.

Now incorporate these data points into your enter selection:

const yValuesArray = [
  [0, 20, 30, 40, 50],
  [0, 200, 250, 400, 450]
];

const xValuesArray = [0, 10, 20, 30, 40];

const dataPoints = yValuesArray.map(dataset =>
  dataset.map((value, index) => ({
    x: xValuesArray[index],
    y: value
  }))
);

const xScale = d3.scaleLinear();
const yScale = d3.scaleLinear();

const lineGenerator = d3.line()
  .x(d => xScale(d.x))
  .y(d => yScale(d.y))
  .curve(d3.curveLinear);

const chartLine = d3.select("svg").selectAll(null)
  .data(dataPoints)
  .enter()
  .append("path")
  .attr("d", lineGenerator)
  .attr("stroke", "blue")
  .attr("stroke-width", 2)
  .attr("fill", "none");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="300" height="400"></svg>

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

Dynamically assigning anchor tags to call JavaScript functions

Creating a list dynamically, full of <span class="infa9span"><img src="/csm/view/include/images/foldericon.png"/><a id="infa9Service">'+servicename+'</a><br/></span> tags. This list is then appended to a div. ...

Issue encountered while trying to render an item from a state array in React

I encountered an issue with retrieving state data within the render function. Everything seems to work fine and displays the array when I utilize console.log(items) However, attempting to access the first item from the array results in an error console. ...

What is the best approach to iterate through multiple input fields while maintaining separate states for each one?

Utilizing Vuetify to create text fields and applying v-model to a textFieldState results in all text fields sharing the same state, causing input from one field to leak into others. How can I ensure that each field maintains its own state? <div v- ...

I am facing difficulty in retrieving a unique dynamic div id using the useRef ReactJS hook, as it keeps returning the same id repeatedly

When using the useRef Reactjs hook, I encountered an issue where it returned the same id repeatedly instead of generating a dynamic div id. I need this functionality to map buttons and div ids in order to create a flexible accordion. The goal is to displ ...

Trouble presenting information retrieved from API

I'm encountering an issue with displaying the data I fetched from an API. I'm not sure what's causing the problem... I attempted to use the map() function to access the data, but it's not functioning as expected either. import React fr ...

What are the reasons behind the lack of smooth functionality in the Bootstrap 4 slider?

My customized bootstrap4 slider is functional, but lacks smoothness when clicking on the "next" and "prev" buttons. The slider transitions suddenly instead of smoothly. Any suggestions on how to fix this? Here is the code for the slider: $('.carous ...

Enclose HTML tags around to ensure all are clickable

I want to make an entire row clickable on my website. Currently, the rows are structured like this: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script src="https://ajax.googleapis.com/aja ...

Tips on duplicating an object within a React state without using references

In my React application, I have a state that contains several objects. I need to make a copy of the c: "value" field from the initial state before it gets replaced by the input value from e.target.value. The purpose behind this is to ensure that ...

Guide to creating jQuery event handlers for active elements

After encountering a frustrating issue with Internet Explorer where an input cursor remained visible behind a div with z-index, I came across a solution here. However, I wanted to convert the solution into jQuery code. Original JavaScript: document.query ...

Remove the export statement after transpiling TypeScript to JavaScript

I am new to using TypeScript. I have a project with Knockout TS, and after compiling it (using the Intellij plugin to automatically compile ts to js), this is my sample.ts file: import * as ko from "knockout"; ko; class HelloViewModel { language: Kn ...

How can one effectively bounce back from a promise that has gone unfulfilled?

As I delve into JS development, I've come across the DRY (Don't Repeat Yourself) concept, which has significantly helped me streamline my code. I'm facing a recurring issue in my project where I find it challenging to enhance without compro ...

Troubleshooting issue: Dexie.js query using .equals not functioning properly in conjunction with localStorage

I am attempting to retrieve a value from indexedDB using Dexie.js, but it seems that the value stored in localStorage is not being recognized. I have tried various methods including async/await, promises, placing the localStorage call in created, mounted, ...

Make sure the first character in Jquery is not a number

When entering text into a textbox, it is important that the first character is not a number. To achieve this, I have written the following code: Check out the DEMO here $('#FieldName').keyup(function (e) { if ($(this).val().length === 1 &am ...

Once you have successfully navigated past Div2, smoothly transition downwards to Div1 and transform it into a sticky

I wish to scroll down, and view #div1... also see #div2... When #div2 disappears from sight, I want #div1 to slide down and stay fixed at the top of the window. If I reach the footer div, I no longer want #div1 to remain sticky. If it's po ...

Latest Version of Joomla includes Jquery 3.4.3 Files

In my Joomla 3.4.3 setup, while debugging in Firefox using Inspect Element, I noticed a message in the console pointing to http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1.8.21/jquery-ui.min.js. Next to this item, it displays: [HTTP/1.1 404 Not Found ...

Step by step guide on serializing two forms and an entire table

I have been attempting to serialize data from two forms and the entire table simultaneously. While the form data is successfully serialized, I am encountering difficulty in serializing the table records as well. Below is the code snippet of what I have att ...

Creating Three-Dimensional Arrays in Print

I am attempting to display a 3D Array. Here is my code snippet: public static void display(int [][][] array) { for (int i=0; i<array.length; i++ ) { for (int x=0; x<array[i].length;x++) { System.out.println(); ...

Discovering elements in Selenium that are dynamically loaded using JavaScript

My endeavor to automate form completion using selenium is being hindered by a peculiar issue. The particular form I am interacting with does not load instantly in the HTML code; instead, it is loaded dynamically through JavaScript after the initial page lo ...

When implementing a helper function in ejs with .then, the result returned is an [ object promise ]

I am facing an issue in my ejs file where I am invoking a helper function from another file that should return a result from MySQL. However, the problem lies in the fact that the returned value is showing as [ object promise ] even though I am using .then( ...

Search for entries that were posted in the previous month

Currently, I am working on a project with Meteor and have encountered a small issue. I believe that many of you may already have the solution. In my setup, I am utilizing MongoDB. My goal is to retrieve posts that were posted starting from the same date ...