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

Tips for updating parameters that are defined in a controller within a promise

Currently, I am developing a single page application using Angular and TypeScript. I am facing an issue with updating the parameter value (_isShowFirst) of the controller inside a promise function. It seems like nothing is recognized within the promise blo ...

The data is not being successfully transmitted to the controller method through the AJAX call

In my JavaScript file, I have the following code: $(document).ready(function () { $('#add-be-submit').click(function (event) { event.preventDefault(); $.ajax({ type: 'POST', url: '/snapdragon/blog/new&apos ...

How can I utilize JavaScript on the server-side similar to embedding it within HTML like PHP?

One aspect of PHP that I find both intriguing and frustrating is its ability to be embedded within HTML code. It offers the advantage of being able to visualize the flow of my code, but it can also result in messy and convoluted code that is challenging to ...

Certain CSS styles for components are missing from the current build

After building my Vue/Nuxt app, I noticed that certain component styles are not being applied. In the DEVELOPMENT environment, the styles appear as expected. However, once deployed, they seem to disappear. All other component styles render properly. Dev ...

Is it possible for me to utilize a validation function to display error messages within a specific span id tag?

document.getElementById("button1").addEventListener("click", mouseOver1); function mouseOver1(){ document.getElementById("button1").style.color = "red"; } document.getElementById("button2").addEventListener("click", mouseOver); function mous ...

Improve the Popup to seamlessly elevate

In my project, I have implemented a pop-up dialog box that rises up from the left bottom corner as the user scrolls down the page. You can view it live at this link- However, I am facing an issue where the initial lift up of the dialog box is not smooth, ...

What is the method to turn off readonly property for input fields in Laravel?

I'm encountering an issue with my Laravel project. I have a form with an input field that has the readonly attribute set. <input type="text" name="anamFam" id="anamFam" value="{{$aFam->anam_cont}}" readonly> When I click the edit button, I ...

Creating collapsible tables with hook functionality in Material-UI

Having trouble resolving this issue, I am seeking assistance with my handleClick() function which is supposed to collapse and expand all table rows simultaneously. The code snippet demonstrating the issue can be found here. Can anyone explain why it is not ...

Automated configuration of AWS Amplify JavaScript using Gitpod

Looking to streamline the setup process for an AWS Amplify JavaScript project on Gitpod. My goal is to eliminate the manual steps of configuring the amplify-cli, such as adding IAM users and generating the aws-exports.js file. Successfully installed the a ...

Javascript variable unable to retrieve value from textbox

Hey there! I am having some trouble reading a textbox that is populated from the server into a JavaScript variable. When I try to access it, I get a console error saying "can't read from NULL". However, the text box is definitely populated with the st ...

What is the optimal arrangement for constructors or classes in JavaScript code?

Constructors, being objects that are stored as copies, appear to behave similarly to variables in terms of their placement within the code. Unlike functions, constructors cannot be placed "anywhere" and must instead be positioned above the area where they ...

Store the output of the function in a variable

Here is a script that was provided to me: <div id="container1"> <script> var script = document.createElement("script"); script.type = "text/javascript"; script.text = 'document.write(xmlDoc.getElementsByTagName("INFO") ...

How to play audio with a source path that includes the special character "%" in JavaScript

Having an issue with playing an audio file that has '%' in its name. I've tried using the tag <audio src="test%320.mp3" controls></audio>, but it seems like the file is not being found when I try to play it. Can anyone ...

What methods are most effective for showcasing Flash messages within Express.js?

I have a Node.js app in the EJS framework and I am new to JavaScript. Could someone please advise me on the correct way to set flash messages in Node.js? Below is my code which is throwing an error: C:\Users\sad\Desktop\Node Applica ...

The functionality of Jquery UI is not compatible with version 1.12

Incorporating jQuery UI into my current project has presented some challenges. Both the jquery-ui.min.css and jquery-ui.min.js files are version 1.12, so I opted for the latest jQuery version, jquery-3.2.1.min.js. Specifically, I decided to test the datep ...

Issue with Gijgo grid not updating properly during change event

I'm currently working on an MVC 5 application and I've hit a roadblock with a particular view. This view contains a dropdown menu and a grid (Gijgo-grid). The grid's content is supposed to change based on the selected value from the dropdown ...

Tips for utilizing the onload function in jquery

Having an issue where I have a button that I want to set time, and in order for the function to run correctly, it needs to be defined on the body element. This works fine with plain JavaScript, but I am encountering an error when trying to use jQuery. < ...

Obtain an Array Following the For Loop

Struggling with grasping the concept of for loops in arrays. I'm attempting to develop a Thank You card generator and here are the steps I am endeavoring to execute: Initialize a new empty array to store the messages Loop through the input array, con ...

The Angular application is receiving a 404 error when trying to access the .NET Core

Having trouble calling a method in the controller via URL, as I keep encountering a 404 error. What could be the issue? API Endpoint: http://localhost:5000/Home/HomeTest /*.net core web-api*/ namespace MyApp.Controllers { Route("api/[controller]") ...

The Angular modal service is failing to show up on the screen

I am having trouble implementing the angular modal service in my web application. When I click on the button, the modal does not appear. Can someone help me figure out what I am doing wrong? Builder View <div ng-controller="BuilderController as vm"> ...