Exploring D3.js version 4.10: Leveraging x-axis timescale with Data retrieval using XMLHttpRequest

I'm currently working with D3.js version 4 and encountering two separate issues. Firstly, I have retrieved data using XMLHTTPRequest which includes a name, an identifying number, and additional data. After my ajax request, the structure of the data appears as follows:

function initialize() {
        var xhr = new XMLHttpRequest();
        var url = "/get_daily";

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                var data = JSON.parse(xhr.response);
                buildCard(data);
            }
        }
         xhr.open('GET', url, true);
         xhr.send();
    }

    […]
0: {…}
daily_available: 73621931016302
daily_total: 74463845381120
daily_used: 841914364818
date: "11-30-2017"
__proto__: Object { … }
1: {…}
daily_available: 73620537623773
daily_total: 74463845381120
daily_used: 843307757347
date: "11-29-2017"
__proto__: Object { … }
2: {…}
daily_available: 73620626989231
daily_total: 74463845381120
daily_used: 843218391890
date: "11-28-2017"

__proto__: Object { … }

I am seeking guidance on how to represent daily_used, daily_total, and daily_available data points on a graph.

The second issue pertains to the x-Axis. The following code snippet represents my xAxis implementation:

 var xScale = d3.scaleTime()
                .domain([
                    d3.min(dataset, function (d) {
                        return new Date(d.date.replace(/-/g, "/"));
                    }),
                    d3.max(dataset, function (d) {
                        return new Date(d.date.replace(/-/g, "/"));
                    })
                ])
                .range([padding, w]);
var xAxis = d3.axisBottom()
                       .scale(xScale)
                       .ticks(dataset.length)
                       .tickFormat(formatTime);

However, there seems to be alignment issues with the dates on the x-axis. The first date/tick is too close to the y-axis while the last tick's date is partially clipped.

https://i.sstatic.net/9F097.png

Your assistance in resolving these issues would be greatly appreciated. Most resources provide examples with simple data sets, making it challenging to address more complex scenarios.

Almost... https://i.sstatic.net/mbKKo.png

Answer №1

Providing a comprehensive solution with detailed comments for your reference

var dataset = [
  {
    daily_available: 73621931016302,
    daily_total: 74463845381120,
    daily_used: 841914364818,
    date: "11-30-2017"
  },
  {
    daily_available: 73620537623773,
    daily_total: 74463845381120,
    daily_used: 843307757347,
    date: "11-29-2017"
  },
  {
    daily_available: 73620626989231,
    daily_total: 74463845381120,
    daily_used: 843218391890,
    date: "11-28-2017"
  }
];


// Defining size and margin
// You have the flexibility to adjust these values directly in the object
var margin = {top: 10, right: 50, bottom: 50, left: 100},
    width = 500 - margin.left - margin.right,
    height = 200 - margin.top - margin.bottom;

// Applying scale based on the defined size
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);

// Setting up x domain using a Date scale
var xDom = [
  d3.min(dataset, function (d) {
  return new Date(d.date);
  }),
  d3.max(dataset, function (d) {
  return new Date(d.date);
  })
];

// Calculating y domain by concatenating values for max and min range
var concat = []
dataset.forEach(function(d) {
  concat.push(d.daily_available);
  concat.push(d.daily_total);
});
var spacing = 1.05; 
var yDom = [
  d3.min(concat) / spacing, 
  d3.max(concat) * spacing
];

// Applying domains
x.domain(xDom);
y.domain(yDom);

// Initializing lines for daily data visualization
var line1 = d3.line()
    .x(function(d) { return x(new Date(d.date)); })
    .y(function(d) { return y(d.daily_available); });
    
var line2 = d3.line()
    .x(function(d) { return x(new Date(d.date)); })
    .y(function(d) { return y(d.daily_total); });
    
var line3 = d3.line()
    .x(function(d) { return x(new Date(d.date));  })
    .y(function(d) { return y(d.daily_used + (d3.min(concat) / spacing)); }); 

// Creating SVG element

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 + ")");

// Drawing lines on SVG

svg.append("path")
  .data([dataset])
  .attr("class", "line")
  .style("stroke", "green")
  .attr("d", line1);

svg.append("path")
  .data([dataset])
  .attr("class", "line")
  .style("stroke", "blue")
  .attr("d", line2);

svg.append("path")
  .data([dataset])
  .attr("class", "line")
  .style("stroke", "red")
  .attr("d", line3);

// Adding X Axis
var formatTime = d3.timeFormat("%m/%d/%Y");
var axisBottom = d3.axisBottom(x).ticks(dataset.length-1).tickFormat(formatTime)
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(axisBottom);

// Adding Y Axis
var axisLeft = d3.axisLeft(y).ticks(5)
svg.append("g")
  .call(axisLeft);

// Lastly, include necessary scripts
 
.line {
  fill: none;
  stroke: gray;
  stroke-width: 0.5px;
}
<script src="https://d3js.org/d3.v4.min.js"></script>

Note: Utilize d3.request() for AJAX requests https://github.com/d3/d3/blob/master/API.md#requests-d3-request

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

Troubleshooting the issue with formatting dates in AngularJS

I need help converting 2015-04-17 12:44:38.0 to dd/MM/yyyy format using angularjs <td ng-bind="item.MON_FE_DUEDATE | date:'dd-MM-yyyy'"></td> However, it is still displaying 2015-04-17 12:44:38.0 only. Can anyone please point out w ...

Achieving two-way data binding in a directive without using an isolated scope

Implementing scope: { ... } in a directive creates an isolated scope that doesn't inherit from its parent. However, my usual practice has been to utilize this for easily declaring HTML attributes with bi-directional data binding: scope: { attr1: ...

Ways to identify when a file download has finished with the help of javascript

let pageUrl = "GPGeneration_Credit.ashx?UniqueID=" + __uniqueId + "&supplierID=" + supplierID + "&CreditID=" + OrderIds; window.open(pageUrl); // Want to check if the file download is complete and then refresh the page location.r ...

The dynamic data is not displaying on the Chart bundle JavaScript

I am currently utilizing chart bundle js for my project. While everything appears to be functioning properly on alter show, I am encountering an issue with the map display – nothing is showing up as intended. If anyone has a solution to resolve this iss ...

React throws an error message when the update depth surpasses its maximum limit

I am facing an issue with my container setup where the child container is handling states and receiving props from the parent. The problem arises when I have two select statements in which onChange sets the state in the child container, causing it to re-re ...

A guide to displaying a countdown timer in an Angular application during the app's loading process

Displaying a loader that shows the time in seconds while loading an app is my goal. Here is the code snippet: HTML <body> <div class="app-loader"> <div class="loader-spinner"> <div class="loading-text"></div> ...

Primefaces: Creating a dynamic accordionPanel with editable objects

I am attempting to create a feature that dynamically generates tabs within a panel based on a list. Let's say the list consists of objects such as Person For each person, I display their attributes in separate tabs within a form. While the initial v ...

What is the best method for typing a component prop that is compatible with singular use and can also function within loops without disrupting intellisense?

The Scenario Within a heading component, I have defined various types as shown below: // Heading/index.d.ts import { HTMLAttributes } from 'react'; export const HeadingType: { product: 'product'; marketing: 'marketing'; ...

Expanding and collapsing UI elements within an ngRepeat loop in AngularJS

I have been attempting to incorporate collapsible panels within an ngRepeat loop. Below is the code I have been using: <div class="panel panel-default" ng-repeat="element in elements"> <div class="panel-heading"> ...

Ajax: What could be causing the post request to be triggered twice?

I am puzzled by the fact that my request is being sent twice, without any clear reason. Here is the code for my simple form: <form method="POST" class="mb-4" autocomplete="off" action="/recipe/add" novalidate id="form"> <div class="form-grou ...

Having trouble interpreting the response using jQuery

Upon running my PHP script, I am receiving the following response. PHP: <?php $con = mysqli_connect("localhost","root","pass","products"); if(mysqli_connect_errno()) { echo "Failed to connect database, please check with your administrator. Error ...

The <servicename> is inaccessible within an error function in Angular2

I encountered an unusual issue in angular2. While the code below is functioning correctly: loginResult.subscribe( (data) => this.response = data, (err) => this._ajaxService.handleError(err, 'A string to summarize th ...

How to Utilize useRef in React Hooks Without Direct Access to HTML Elements?

When working with React, I find myself in a situation where the HTML elements are being loaded from a separate repository that I monitor using pageLoaded. The updateHeader function contains more code for selecting HTML elements and manipulating attributes/ ...

Breaking down arrays using the JADE Template Engine

Currently, I am utilizing the JADE template engine in conjunction with ExpressJS. I am attempting to pass an array to my JADE template like so: var data = { "labels" : ["Label 1", "Label 2"] }; res.render('index', {data: data}); The struct ...

Add a preventDefault event listener to a submit button that triggers a specific function

$(function() { $('#login').submit(function(e){ preventSubmission(); e.preventDefault(); }); }); function preventSubmission() { $('#btnLogin').attr('disabled','disabled'); $("#btnLogi ...

ESLint flagging "Unexpected tab character" error with "tab" indentation rule enabled

Currently, my ESLint setup includes the Airbnb plugin (eslint-config-airbnb) along with the Babel parser. I recently decided to enforce the rule of using Tab characters for indentation instead of spaces. This is how my .eslintrc file looks like: { "p ...

What is the best way to parse a JSON file and create a dynamic webpage using jQuery with the data from the

As someone who is new to working with Node.js and JSON, I am encountering some issues when trying to extract data from a JSON file. Below is the code that I have written: 'use strict'; const fs = require('fs'); let questsRawData = fs ...

When it comes to optimizing JavaScript, what is the best approach for replacing multiple substrings in a string with various strings?

While working on the code I develop and maintain, I encountered an issue. There is a function in my code that takes a query (in the form of a string) and replaces certain substrings within that string with different ones. For instance, if a user inputs th ...

Invoking a Spring Controller from jQuery with an extra parameter

When a text field is changed, jQuery triggers a call to the Spring Controller. I am wondering how this query sends the @RequestParam to the Controller method controller/find. Is there a way to include additional Param in this call? $(document).ready(func ...

What is the best way to incorporate an npm module in a django-admin widget without the need to install node?

Background I am working on a Django app and need to create an admin widget. The widget will display text in a unique terminal-style format to show forwarded logs from an analytics process managed by Django (using the django-twined extension). To achieve ...