Creating a line graph with d3.js

I am currently working on implementing a line chart using data in JSON format following the steps outlined in this tutorial:

[{"Machine":"S2","Data":[{"Percentage":0,"Week":33,"Year":2014,"Monday":"11/08/14","Items":0},{"Percentage":0,"Week":34,"Year":2014,"Monday":"18/08/14","Items":0},{"Percentage":0,"Week":35,"Year":2014,"Monday":"25/08/14","Items":0},{"Percentage":0,"Week":36,"Year":2014,"Monday":"01/09/14","Items":0},{"Percentage":1.141848548192784,"Week":37,"Year":2014,"Monday":"08/09/14","Items":2},{"Percentage":58.264732011508123,"Week":38,"Year":2014,"Monday":"15/09/14","Items":4},{"Percentage":0,"Week":39,"Year":2014,"Monday":"22/09/14","Items":0}]},{"Machine":"S3","Data":[{"Percentage":0,"Week":33,"Year":2014,"Monday":"11/08/14","Items":0},{"Percentage":0,"Week":34,"Year":2014,"Monday":"18/08/14",...

<p>This is the code I have implemented:</p>

<pre><code>function CreateOeeChart(json) {
// Define canvas / graph dimensions
var margin = {top: 30, right: 20, bottom: 30, left: 50},
    width = 600 - margin.left - margin.right,
    height = 270 - margin.top - margin.bottom;

// Parse date/time values causing issues
var parseDate = d3.time.format("%d/%m/%Y").parse;

// Set ranges for x and y axes
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

// Axes definitions
var xAxis = d3.svg.axis().scale(x)
    .orient("bottom").ticks(5);

var yAxis = d3.svg.axis().scale(y)
    .orient("left").ticks(5);

// Line definition
var line = d3.svg.line()
    .x(function(d) { return x(d.Monday); })
    .y(function(d) { return y(d.Percentage); });

// SVG canvas creation
var svg = d3.select("#oeeChart")
    .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 + ")");

// Modify date data
jsonString.forEach(function (d) {
    d.Data.forEach(function (v) {
        v.Monday = parseDate(v.Monday);
    });
});

// Data range scaling
x.domain(d3.extent(jsonString, function (d) {
    d.Data.forEach(function (v) {
        return v.Monday;
    });
}));
y.domain([0, 100]); 

// Loop through JSON object to draw lines
jsonString.forEach(function (d) {
    svg.append("path")
        .attr("class", "line")
        .attr("d", line(d.Data));
});

// Adding X Axis
svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

// Adding Y Axis
svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

}

Encountering an error "Invalid value for path attribute..." while trying to append path elements could be due to incorrect data formatting or parsing. Double-check the JSON structure and how data is being extracted for plotting.

Answer №1

When dealing with a nested structure like this, d3.extent cannot be used directly to determine the domain. The correct approach involves extracting the minimum and maximum values for each individual nested array, followed by calculating the overall minimum and maximum:

var min = d3.min(jsonString, function (d) {
  return d3.min(d.Data, function (v) {
    return v.Monday;
  });
});
var max = d3.max(jsonString, function (d) {
  return d3.max(d.Data, function (v) {
    return v.Monday;
  });
});
x.domain([min, max]);

You can find a complete demonstration here. Another option is to flatten the array of arrays of dates into a single-level array before determining the extent.

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

Receiving an 'undefined' result in an asynchronous response even with 'await' and 'then' statements implemented

I'm struggling with sending a GET request, parsing the response, and passing it to another function. It seems like I'm having difficulty dealing with the asynchronous nature of the response. I prefer to stick to using Node.js' built-in modu ...

Django REST Framework: Converting Data to JSON and Fetching it Using JavaScript from my API

How can I retrieve data from my API using JavaScript? My objective is to present my model data in the form of charts or graphs. For the visualization part, I have chosen Charts.js. Currently, I am able to display a chart in my template with default data. ...

Is there a similar function in PHP to creating an array with a specified number of elements in JavaScript using "new Array(number)"?

While attempting to convert a basic Javascript function into PHP, I encountered a variable declared as var Variable = new Array (13). In PHP, variables are typically declared like this: $variable = array() But what does the "13" in new Array(13) signify? ...

Bundling and minifying Angular2 assets

In the world of ASP.NET (or gulp), bundling and minification are taken care of. However, a different issue arises when following Angular2 tutorials: the view HTML is typically embedded within the component itself. Fortunately, there is a way to separate th ...

The reason for the lack of auto complete functionality in this specific Bootstrap example remains unclear

I've been attempting to implement an auto-complete dropdown feature with dynamic data, but I'm facing an issue where no suggestions are displayed in the dropdown. I found this example on Datalists: https://getbootstrap.com/docs/5.1/forms/form-con ...

Update the image links to automatically refresh every half a second based on the values inputted in the text bars

Is there a better and simpler way to define AAAAAAAAAA, BBBBBBBBBB, and CCCCCCCCCC using the links provided in the text bars named chart1, chart2, and chart3? This learning project is being done through Notepad++ for personal use only, with no need to sa ...

The de-duplication feature in webpack is not functioning properly when the splitChunks cacheGroups commons option is activated

In my lerna project, I have two identical packages named p1 and p2. Both p1 and p2 utilize a 3rd party package - in this case, eosjs@beta, which is approximately 50KB in size. When I incorporate p1 into an example react project, the package size increase ...

Identifying strings from an array in the input using JavaScript and then displaying the identified string

Can you help me create a function that will detect if a user types one of the strings from a list and then output which string was typed in the console? HTML <input id="inputText"></input> JS window.onload = function(){ var inputText = do ...

Transitioning from webpack to vite with Vue.js for a Chrome extension development project

I am currently developing a Chrome extension using Vue.js. I have a project ready to start with, but it is set up with webpack. Within webpack, I have multiple entry points that result in the generation of HTML files and others with JavaScript only. Whil ...

The information being fetched from the API via the service to the component appears to be in object form and may require conversion to an array format for compatibility

Whenever I receive data, one set works perfectly while another set does not Data that is functioning properly looks like this data: Array(16) On the other hand, the problematic data appears as follows data: Menu1Items: Array(5) > 0 { .... } etc ...

unable to activate toggleclass('d-block') for multiple radio inputs

We have multiple radio input options. function showReferral() { document.querySelector('#referral_code').classList.remove('d-none'); } <div class="form-group row d-none" id="referral_code"> <label for="referral_code"&g ...

Utilizing Props in React to Slice and Dice Data Within a Separate Component

Currently, I am in the process of creating an about text for a profile that will include an option to expand or collapse based on its length. To achieve this, I am utilizing a function from the main home component: <AboutText text={aboutData}/> Abo ...

Unusual class exhibiting peculiar async/await patterns

Node 7.9.0 The situation goes like this: class TestClass { constructor() { const x = await this.asyncFunc() console.log(x) } async asyncFunc() { return new Promise((accept) => { setTimeout(() => accept("done"), 1000) }) ...

execute action after a specific point in time in the video is reached

How can I hide a div after a video has been playing for a certain amount of time? The code provided below seems like it should work in theory, but is currently not doing so. Any suggestions on how to fix this issue would be greatly appreciated! <body ...

What happens if setTimeout fails due to a page error?

My current setup involves using setTimeout to refresh the page, updating the jQuery template items. Here is a snippet of the relevant code: <script type="text/javascript"> var results = JSON.parse('@svgPath'.replace(/&quot;/g ...

Using TypeScript, let's take a closer look at an example of Angular

I am trying to replicate the chips example found at this link (https://material.angularjs.org/latest/#/demo/material.components.chips) using TypeScript. I have just started learning TypeScript this week and I am having some difficulties translating this co ...

Creating a JQuery statement to conditionally change CSS values

Is there a way to determine if a div element with a CSS class of "x" has a height set to "auto"? If so, I would like a jQuery script to remove the CSS class "a" from all elements with the class "y". If not, the script can remain unchanged. Thank you. ...

Surprising Vercel Production Problem: Functions in Development Environment but Fails in Production Even After Reverting to a Functional Commit

In the development environment, everything runs smoothly without any issues. However, when the application is deployed to production, errors start cropping up. What's puzzling is that even after reverting to a previous commit where the production was ...

What is the best way to retrieve data from an external JSON file using jQuery?

This is my app.js file $(document).ready(function () { $.getJSON("http://localhost:3000/db.json", function (data) { $(data.as).each(function (index, value) { console.log(value); }); }); }); and this is db.json f ...

Transmitting Various Static Files via Express Router

I am currently utilizing the Express router to serve static .html files based on the URL specified in router.get. For example, this code snippet sends the homepage: router.get('/', function(req, res, next) { res.sendFile('index.html&ap ...