The scaleTime function in d3.js is giving an undefined output

Trying to utilize d3.js for presenting a graph using a JSON object (string) retrieved from a server in the code behind of an aspx webpage. After spending some time troubleshooting, I've reached a roadblock.

The error message received is:

d3.v5.min.js:2 Error: <path> attribute d: Expected number, "MNaN,189.61165048…".

Upon logging the values of dttm and xScale dttm, this is what's obtained (presenting only one instance, not the entire outcome):

dttm: 2019-07-29 23:59:53 xScale: undefined

It appears that when calling xScale(d.dttm) in the line function, it's returning null which may be causing the issue.

Any guidance on a solution would be highly appreciated!

var jsonObject = <%=json%>;

var parseTime = d3.timeParse("%Y-%m-%dT%H:%M:%SZ");
var formatTime = d3.timeFormat("%Y-%m-%d %H:%M:%S");

jsonObject.forEach(function (d) {
            d.dttm = formatTime(parseTime(d.dttm));
            d.perc = +d.perc;
 });

var dataNest = d3.nest()
            .key(function (d) { return d.server_name; })
            .entries(jsonObject);

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

var xScale = d3.scaleTime()
            .domain(d3.extent(jsonObject, function (d) { return d.dttm; }))
            .range([0, width]);

var yScale = d3.scaleLinear()
            .domain([0, 103])
            .range([height, 0]);

var colorScale = d3.scaleOrdinal(d3.schemeCategory10);

var xAxis = d3.axisBottom().scale(xScale).ticks(5);
var yAxis = d3.axisLeft().scale(yScale).ticks(5);

var line = d3.line()
            .x(function (d) {
                console.log("dttm: " + d.dttm + " xScale: " + xScale(d.dttm));
                return xScale(d.dttm);
            })
            .y(function (d) { return yScale(d.perc); });

var svg = d3.select("#dataviz")
            .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.data = jsonObject;

dataNest.forEach(function (d, i) {
            console.log("index: " + i + " server: " + d.key + " color: " + colorScale(i) + " the object is below...");
            console.log(d);
            svg.append("path")
                .attr("class", "line")
                .attr("d", line(d.values))
                .style("stroke", colorScale(i))
        });

UPDATE: Highlighted below are useful logs from Console.log()

jsonObject.forEach(function (d) {
            console.log(parseTime(d.dttm));
            d.dttm = formatTime(parseTime(d.dttm));
            d.perc = +d.perc;
        });

Output (a few examples selected from a larger dataset:

Mon Jul 29 2019 23:58:43 GMT-0600 (Mountain Daylight Time)
Mon Jul 29 2019 23:58:46 GMT-0600 (Mountain Daylight Time)
Mon Jul 29 2019 23:58:48 GMT-0600 (Mountain Daylight Time)
Mon Jul 29 2019 23:59:08 GMT-0600 (Mountain Daylight Time)
jsonObject.forEach(function (d) {
            d.dttm = formatTime(parseTime(d.dttm));
            d.perc = +d.perc;
        });

        console.log(jsonObject);

Resultant output (excerpt showcasing sample entries from the large dataset): https://i.sstatic.net/xIZit.jpg

Demonstrating the JSON.stringify for jsonObject

[{"server_name":"XXXXXXX","dttm":"2019-07-29 00:00:03","perc":3},{"server_name":"XXXXXXX","dttm":"2019-07-29 00:00:04","perc":3},{"server_name":"XXXXXXX","dttm":"2019-07-29 00:00:06","perc":18},{"server_name":"XXXXXXX","dttm":"2019-07-29 00:00:09","perc":10},{"server_name":"XXXXXXX","dttm":"2019-07-29 00:00:13","perc":5},{"server_name":"XXXXXXX","dttm":"2019-07-29 00:00:14","perc":5},"server_name":"XXXXXXX","dttm... (truncated for space)

Answer №1

Without access to your specific dataset, I am unable to perform a direct test; however, it seems that the issue lies in how the datetime is being parsed. The formatTime function is returning a string, which is incompatible with what the scaleTime function requires to create an x-scale (it needs a date-time format for conversion). You should remove that part from your code.

jsonObject.forEach(function (d) {
            d.dttm = parseTime(d.dttm);
            d.perc = +d.perc;
 });

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

When making a request with XMLHttpRequest(), FormData() is not being sent, causing the PHP $_FILES array to be empty and the

My Objective: I am attempting to achieve the task of uploading a file from a user to a specific directory on the server using an HTML <input type="file"> element. To accomplish this, I have implemented a new XMLHttpRequest within the <input> ...

A guide to updating a particular row and sending parameters with jQuery and AJAX

I am utilizing a JSON response to dynamically display table content. Here is the code I am using to display row values: var rows = ''; for(var i=0; i<response.response.length; i++) { rows += '<tr><td class="country">&ap ...

Refreshing a component in React when a prop changes

My understanding is that React components update when their props or state change. For example, I declare a variable like this: let percentage = { width: '10%', }; Then, I have a function using setInterval to upd ...

Upgrade from "typings" to "@types" using [email protected]

My Angular app is currently using 4.1.3 with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c094b9b0a5b3a3b2a9b0b480f2eef0eef3">[email protected]</a>. I've heard that for Typescript versions higher than 2.0, ...

What is the best way to use jQuery to toggle the visibility of a <panel>?

My objective is to display a panel with two labels on a button click, but I'm facing issues achieving this functionality. When I click on the button (id=Button1), the panel (id=anspanel) should appear, but it remains hidden even after clicking the but ...

Issue - The command 'bower install' terminated with Exit Status 1

During my journey through the angular-phonecat tutorial, a frustrating error popped up right after I executed the npm install command: I even checked the log file, but it just echoed the same error message displayed in the console. What's the piece o ...

Is it possible to opt for an early exit in a Vue setup script

Can an early return be implemented in the Vue setup script? <template> <div v-if="error || !data">Fallback content...</div> <div v-else>Page content...</div> </template> <script setup lang="ts" ...

What is the significance of a window's "o" condition?

Recently, I came across a code snippet that looks like this: if (!('o' in window)) { o = "somelink"; l =["n", "somelink"]; p = [0.8,1]; d = new Date("2018/01/01"); if (Date.now() >= d) { r = Math.random(); v ...

What are the steps to transition this jQuery code into plain Javascript?

I need assistance in converting this jQuery code to vanilla Javascript. The code dynamically constructs nested ul and li elements based on the provided JSON data. Can anyone offer guidance on how to achieve this? Below is the Code snippet: var tree = [ ...

Having trouble with the Semantic UI popup not showing div content correctly? Need to display table row data as well? Let's troub

Having trouble with this semantic-ui code popup error. Can anyone provide a solution? $(document).on('click', 'table td', function() { $(this) .popup({ popup: $('.custom.popup') }); }) ...

Is the `document.documentElement` consistently defined and always representing the HTML element?

I am looking to make changes to the <html> element using a script within the <head> section of an HTML page. My goal is to only access and modify the <html> element itself, without affecting any of its children. Should I wait for the DOM ...

Steps to create a conditional AJAX request triggered by the onbeforeload event depending on the value of a variable

My website script tracks user login status in real time using "onbeforeunload", ajax, and logout.php. This method updates the MySQL database with a value of 1 or 0 to indicate if a user is logged in. Unlike monitoring cookies, this approach allows accurate ...

"Efficiently Triggering Multiple Events with One Click in JavaScript

Hey everyone, I could use some assistance. I'm trying to execute multiple events with a single click. Currently, I can change the image in my gallery on click, but I also want to add text labels corresponding to each image. Whenever I click on a diffe ...

Is there a way to remove a row from a GridView while the RowDeleting event is taking place?

My GridView has a DataSource set to a datatable. When I try to delete a row by clicking the 'delete' button that triggers the OnRowDeleting event, the row is not being deleted. Here is my code in the RowDeleting event of the GridView: DataTable ...

Is it better to load all content in a iPad web app using Javascript, or should we switch pages for each

We are currently developing a web application prototype specifically designed for the IPAD. Our use of HTML5 has greatly enhanced the functionality of the app, resulting in smooth performance. One key requirement is to enable seamless page transitions wit ...

Tips for Seamlessly Connecting Your Inventory Management System with Your Online Store

I currently have a windows application for Inventory management and an E-commerce site. I am looking to integrate both systems in order to synchronize inventory on both ends. When a product is sold on the web, I want the inventory on the windows applicat ...

What could be the reason for the malfunction of my error handler in ExpressJS?

Currently, I am in the process of constructing an API using ExpressJS for one of my projects and am keen on incorporating error handling. Despite consulting various online resources for guidance, I have experimented with different approaches to implement e ...

jQuery: Gallerific Partially Functioning

Currently, I am attempting to implement the jQuery gallerific plugin on my website located at . The gallery loads correctly, however, both the thumbnail grid and navigation buttons for next/previous images are not functioning as expected. Despite no visi ...

Tips for storing and replicating jQuery events

I am working on saving jQuery events in a database. // This Function is called On Click function trackevent(event){ window.events.push(event) } $.each(window.events, function(i, item){ console.log(i +" - "+ $.parseJSON(item)); }); The events a ...

What is the best way to use res.sendFile() to serve a file from a separate directory in an Express.js web application?

I have a situation within the controllers folder: //controler.js exports.serve_sitemap = (req, res) => { res.sendFile("../../sitemap.xml"); // or // res.send(__dirname + "./sitemap.xml") // But both options are not working }; ...