d3js graphics, Opt for utilizing json strings over json file

My first experience with d3js was while utilizing the Line Chart Sample provided by this link. Despite successfully loading the data as seen in Firebug, the chart itself failed to display the data. I am unable to identify the issue and would greatly appreciate any assistance.

Here is the code I am working with:

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

var parseDate = d3.time.format("%d-%b").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.timeStamp);
    })
    .y(function(d) {return y(d.memberAverageLoadAverage); });

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


var json1=[
{
    "clusterId": "",
    "timeStamp": 1437063744524,
    "memberAverageLoadAverage": 20,
    "memberId": ""
},
{
    "clusterId": "",
    "timeStamp": 1437069850060,
    "memberAverageLoadAverage": 20,
    "memberId": ""
},
{
    "clusterId": "",
    "timeStamp": 1437069910059,
    "memberAverageLoadAverage": 20,
    "memberId": ""
},
{
    "clusterId": "",
    "timeStamp": 1437069970060,
    "memberAverageLoadAverage": 20,
    "memberId": ""
},
{
    "clusterId": "",
    "timeStamp": 1437070030056,
    "memberAverageLoadAverage": 20,
    "memberId": ""
}

];

root = json1;

  x.domain(d3.extent(root, function(d) { return d.timeStamp; }));
  y.domain(d3.extent(root, function(d) { return   d.memberAverageLoadAverage; }));

  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("memberAverageLoadAverage");

  svg.append("path")
      .datum(root)
      .attr("class", "line")
      .attr("d", line);

Answer №1

By making some adjustments to the code, including removing the JSON.parse for the JS object and modifying the memberAverageLoadAverage values to avoid them all being the same, I successfully rendered a graph. The issue I encountered was that the extent call was causing the y axis to range from 20 to 20, resulting in the line being positioned at the bottom of the screen and intersecting with the x axis. To address this problem, I recommend setting the y.domain to [0, d3.max(...)] instead of relying on d3.extent.

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

var parseDate = d3.time.format("%d-%b").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.timeStamp); })
    .y(function(d) {return y(d.memberAverageLoadAverage); });

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


var json1=[{"clusterId":"","timeStamp":1437063744524,"memberAverageLoadAverage":11,"memberId":""},{"clusterId":"","timeStamp":1437069850060,"memberAverageLoadAverage":5,"memberId":""},{"clusterId":"","timeStamp":1437069910059,"memberAverageLoadAverage":6,"memberId":""},{"clusterId":"","timeStamp":1437069970060,"memberAverageLoadAverage":15,"memberId":""},{"clusterId":"","timeStamp":1437070030056,"memberAverageLoadAverage":20,"memberId":""}];

var data = json1;

  x.domain(d3.extent(data, function(d) { return d.timeStamp; }));
  y.domain([0, d3.max(data, function(d) { return d.memberAverageLoadAverage; })]);

  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);
.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 1.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №2

It would be ideal to treat this as a comment, but I have a few recommendations. Firstly, I propose utilizing externally loaded JSON data if you have access to a server for making HTTP requests. If not, you can opt for local data, but in any case, you need to incorporate a data.foreach function where you define all your values, akin to the example below.

data.foreach(function(d) {
    d.timeStamp = d.timeStamp;
    d.memberAverageLoadAverage = +d.memberAverageLoadAverage;
});

Moreover, I highly recommend reorganizing your JSON structure as the current keys are not very well implemented. I suggest reviewing the data restructuring options available here and making the necessary changes. Feel free to update me on your progress and let me know if you require further assistance.

Answer №3

Deciphering this might be a challenge since it appears to be an array. Regardless, trying to parse it may not be necessary.

  `let data=`[{"id":"1234","timestamp":1437063744524,"value":20,"name":""},

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

Extract data from a webpage using Python and AJAX operations

With my knowledge of scraping HTML using Python's Beautiful Soup, I encountered a challenge with this soccer statistics page that utilizes AJAX to retrieve data on minutes played by a player. (I discovered the network call through firebug). I'm ...

Merging angular-file-upload with multer

I am facing a challenge in integrating the angular file upload plugin with multer to create a fully Single Page Application (SPA). I am currently stuck on uploading multiple files through multer. Below is how my multer options are set up in my node route. ...

Step-by-step guide to obtaining a Retrofit response in Kotlin

I'm attempting to parse JSON with Retrofit for the first time and I could use some guidance. This is an example of the JSON data: { "results": [ { "idEvent": "576561", "idSoccerXML": "389946", "strEvent": "Liverpool vs Cardi ...

Exploring CakePHP 3's capabilities with JSON response: Enhancing response data format by connecting with related tables

I am working with two tables, each with their own set of attributes: Sessions id staff_id Staff id firstname lastname When a link is clicked, it triggers a JavaScript function to open a modal. An AJAX call is then made to retrieve data in JSO ...

Unusual shadow effects with three.js

I'm still new to three.js and webgl, and I'm encountering some odd-looking shadows when using a directional light. Could somebody help me out? Below is the code I have for the renderer: this.renderer.shadowMapEnabled = true; this.renderer.shad ...

Encountering issues with formData in nextjs 13 due to incorrect data type

In my NextJS application, I am using the dataForm method to retrieve the values from a form's fields: export async function getDataForm(formData) { const bodyQuery = { ....... skip: formData.get("gridSkip") ...

A guide on iterating through a JSON object fetched using Http in Angular 2/Typescript

I am attempting to extract specific data from my JSON file using http. The structure of the JSON is as follows: [{"name":"Name1","perc":33},{"name":"Name2","perc":22},{"name":"Name3","perc":41}] To loop through this retrieved object, I use the following ...

Is there a way to prevent the window.status from appearing?

I currently have the following code snippet: <a class="button accessLink" id="loginLink" href="#" data-action="Login" data-dialog="access" data-disabled="false" data-entity="n/a" ...

Tips for creating a shift function without using the splice method

I'm currently working on creating custom functions for common array operations. I've hit a roadblock trying to reimplement the shift method without using splice. Any tips or guidance on how to approach this challenge would be highly valued. Cust ...

Node.js Express: Breaking Down Your Application into Modules

Currently, I am working on an express app and have the following code setup: MainApp.js const express = require('express'); const routes = require('./routes') const mainApp = express(); mainApp.listen(3000, () => { console.l ...

Issue with Ionic 2's infinite scroll not triggering method on second scroll attempt

I utilized the ion-tab element to showcase a page (inboxitem) which encompasses ion-list and makes use of ion-infinite-scroll. The following code snippet resides in inboxitem.html <ion-content class="inbox can-swipe-list"> <ion-list> ...

Solving Angular Circular Dependencies

My popupservice allows me to easily open popup components: export class PopupService { alert() { this.matdialog.open(PopupAlertComponent); } yesno() { this.matdialog.open(PopupYesNoComponent); } custom() { this.matdialog.open(PopupCustomCompon ...

What steps can I take to ensure that this input is neat and tidy

I need to implement conditional styling for my input field. The current layout is chaotic and I want to improve it. Specifically, when the active item is "Height", I only want to display the height value and be able to change it using setHeight. const [a ...

Leveraging the power of JavaScript to retrieve data from BigQuery

Having just started my journey with JavaScript and Google BigQuery, I am seeking help due to my lack of experience in these areas. My goal is to create a javascript code that can fetch data from one of the public databases on BigQuery. I came across a solu ...

Inquire about understanding Mean.js through form submission

Hey there, I'm looking to create a search engine for an application using JS MEAN. I have a database with various elements and I want users to fill out a form to see the results in a separate view. I haven't had much luck so far, I've don ...

Ways to utilize information from a JQ key for naming a fresh JSON document

After coming across the code shared by @peak in a discussion on how to split a JSON file into separate files, I made some modifications to suit my needs. The solution provided by @peak was truly a lifesaver and saved me countless hours of work. Although t ...

Struggling to capture an error generated by Sequelize within a universal Middleware block

In a test project, I have successfully implemented CLS transaction control in Sequelize using 'cls-hooked'. The transactions work seamlessly both in the command line and with Express. They are injected and managed automatically, rolling back on a ...

Showcasing diverse content with an Angular Dropdown Menu

I'm currently developing an angular application, and I've encountered a difficulty in displaying the user's selection from a dropdown menu. To elaborate, when a user selects a state like Texas, I want to show information such as the period, ...

Update the CSS styling for elements that are dynamically added to the page using the

Just started using jQuery for the first time and I'm encountering an issue. I'm trying to load content from an external element onto my page, and while it loads correctly, I'm having trouble using normal traversal methods on the loaded eleme ...

error": "Unable to access undefined properties (reading 'SecretString')

Encountering the error message Cannot read properties of undefined (reading 'SecretString') when utilizing @aws-sdk/client-secrets-manager? It's a sign that you should consider updating your code to accommodate the latest version. ...