What are the steps to generate a multiline chart using d3.js with json data specifically formatted for nvd3?

I attempted to create a multi-line chart using nvd3, but encountered roadblocks when trying to make significant modifications. I am considering building my own chart using d3js directly, but I'm finding it challenging to grasp the concept of 'thinking in joins'.

My goal is to generate a path for each d.key along with its corresponding set of d.values.

The structure of my data for nvd3 looks like this (simplified).

[
    {
        "key":"brw-a",
        "values":[
            ["2012-07-11T00:00:00", 0.0 ],
            ["2012-07-11T23:59:59", 0.0 ],
            ["2012-07-05T06:31:47", 0.0 ],
            ["2012-07-05T23:59:59", 0.0 ]
        ]
    },
    {
        "key":"brw-c",
        "values":[
            ["2012-07-11T00:00:00", 0.0 ],
            ["2012-07-07T00:00:00", 2.0 ],
            ["2012-07-05T23:59:59", 4.0 ]
        ]
    }
]

It seems that I need to use an inner loop to access the array within each d.values. A working example demonstrates how d.values appears as one large unorganized chunk.

var p = d3.select("body").selectAll("p")
        .data(data)
      .enter().append("p")
        .text(function(d) {return d.key +":  " + '[' + d.values + ']'})

I feel like I'm getting closer, and it likely has something to do with:

.data(data, function(d) { return d.key; })

Update: I managed to manually iterate over the data to achieve the desired outcome. It could be that using joins may not be suitable for this task? Unless utilizing the fantastic nvd3 library, of course. Refer to the comment below for the link.

var body = d3.select("body")

for (i=0; i < data.length; i++) {
    var key = data[i].key
    var values = data[i].values

    body.append("h3")
        .text(key)

    for (j=0; j < values.length; j++) {
        body.append("p")
            .text(values[j][0] + " -- " + values[j][1])
    }

}

Answer №1

Your understanding of the .data() function was correct. To loop through elements in the values array, you need to pass it as data for a nested selection:

.data(function(d) { return d.values})

You can implement this approach like so:

var p = d3.select("body").selectAll("p")
        .data(data)
      .enter().append("p")
        .attr("id", function(d) { return d.key})
        .text(function(d) {return d.key})
            .selectAll("span")
                .data(function(d) { return d.values})
                .enter().append("span")
                    .text(function(d) {return d})

This code will generate something like this:

<p id="brw-a">brw-a
    <span>2012-07-05T00:00:00,0</span>
    <span>2012-07-06T23:59:59,1</span>
    <span>2012-07-07T06:31:47,0</span>
    <span>2012-07-08T23:59:59,3</span>
</p>

<p id="brw-c">brw-c
    <span>2012-07-11T00:00:00,0</span>
    <span>2012-07-07T00:00:00,2</span>
    <span>2012-07-05T23:59:59,4</span>
</p>

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

searching for unspecified information in node.js mongodb

I am encountering an issue while trying to retrieve data from the database after a recent update. The code snippet result.ops is not functioning as expected in MongoDB version 3.0. I am receiving undefined in the console output. Can someone guide me on the ...

Can Angular JS apply the uppercase filter to a boolean value?

My Angular 1.4.12 binding looks like this: {{ mob.mobDataSettings[7].value | uppercase }} The first part is a boolean value from a JSON file, which can be either true or false. But when rendered in HTML, it is not showing up as uppercase (e.g. TRUE), in ...

Struggling to retrieve information using the filter() method in MongoDB

I am currently attempting to retrieve the tasks assigned to a specific user using this setup router.get('/all', auth, async (req, res) => { try { const assignments_raw = await Assignment.find({listP: listP.indexOf(req.user.userId)}) ...

Challenges with handling callbacks in Javascript

I'm currently working on creating a user-friendly GUI using the w2ui library, but I've encountered an issue with integrating a toolbar into my main layout. The problem arises when the toolbar is added before the layout is fully constructed. Sinc ...

Creating custom ExpectedConditions with Protractor for detecting attribute changes

I've been working on creating a custom ExpectedConditions method that can wait for an element attribute to change. Here is the approach I came up with: const CustomExpectedCondition = function() { /** * Check if element's attribute matches ...

Variable remains unchanged by method

I am currently working on an app that utilizes the user's webcam. In case navigator.getUserMedia fails, I need to change the error variable to display the appropriate error message instead of the stream output. Since I am new to Vue, please bear with ...

Is there a way to restrict the orientation of a UIWebView using JavaScript or HTML?

Currently, I am working on HTML content for an iPad application. The challenge at hand is locking the UIWebView's content to portrait mode. Despite having already submitted the app to Apple, I have only come across a solution in this question, which s ...

Error: JSON parsing failed due to an unexpected token "u" at the beginning of the JSON string. This occurred in an anonymous function when

Implementing reCaptcha in my firebase project has been successful. I am now sending form data and the captcha response using grecaptcha.getResponse() to my server upon clicking the send button. Below is the code snippet from client.js: $('.sendUrl ...

JEST does not include support for document.addEventListener

I have incorporated JEST into my testing process for my script. However, I have noticed that the coverage status does not include instance.init(). const instance = new RecommendCards(); document.addEventListener('DOMContentLoaded', () => ...

Even when using module.exports, NodeJS and MongoDB are still experiencing issues with variable definitions slipping away

Hello there, I'm currently facing an issue where I am trying to retrieve partner names from my MongoDB database and assign them to variables within a list. However, when I attempt to export this information, it seems to lose its definition. Can anyone ...

Tips for calculating the canvas-relative mouse position on a CSS 3D transformed canvas

Recently decided to challenge myself by experimenting with drawing on 3D transformed canvases. After some trial and error, I managed to get it partially working. const m4 = twgl.m4; [...document.querySelectorAll('canvas')].forEach((canvas) =& ...

The ViewChild from NgbModalModule in @ng-bootstrap/ng-bootstrap for Angular 6 is causing the modal to return as

I have successfully integrated ng bootstrap into my project, specifically utilizing the modal module to display a contact form. The form includes input fields for email and message, as well as a submit button. You can find the ngbootstrap module I am using ...

Guide to sending a response to an AJAX post request in Express with Node.js: Answered

For a project focused on practicing Node.js and jQuery Ajax, I'm working on a simple task. Essentially, I have an ajax post request that sends data to a Node.js server and waits for a response. On the server-side, there's code that processes this ...

Is it possible to implement a while loop in React?

Issue: I am facing a challenge while attempting to generate an array of 4 elements from a list using a while loop, but it seems to result in an infinite loop. const [options, setOptions] = useState([]); const fetchElements = () => { while(options. ...

The hit detection algorithm seems to be malfunctioning, and the reason behind it is unclear. (Using Javascript/Processing

I am a beginner in game programming and programming in general. In the past, I have created a clone of "Flappy Bird" and some other games using the hit detection algorithm from the Mozilla Developer Network here. Currently, I am facing an issue while tryi ...

Using an HTML element to pass a variable into a replace function

I am looking to highlight a 'SearchString' by replacing it with <span style="background-color: yellow">SearchString</span> within a targetString. The SearchString varies, so I am wondering how I can make this happen. This is what I ...

"Hidden panels in Sencha Touch only respond to show() and hide() methods after a resize event

Check out this demonstration of a Sencha Touch app by visiting this link. The button located in the bottom-left corner is supposed to show or hide the menu panel on top of the "Location info goes here" bar, but it seems to be functioning in an unexpected m ...

Retrieve the red, green, and blue components of a color in the RGB format

When I retrieve "rgb(18, 115, 224)" from a DOM element, I need to convert this color to hexadecimal in order to assign it to a span element. To get the hexadecimal equivalent of the color, I can use the following code snippet: "#" + componentToHex(r) + co ...

Update the text on the button when tasks are in progress in React

I am working on a React project and I need to implement a button that changes its text from Save to Saving... when clicked, and then back to Save once the saving process is complete. My initial approach looks like this: import React from 'react&apos ...

Tips for personalizing the css styles of an alert box?

I am in need of customizing the alert box using CSS attributes. Currently, I am able to achieve a similar effect with the code below: JQUERY: $('<div class="alertMessage">Error first</div>') .insertAfter($('#componentName' ...