"Utilizing JSON information to create visually appealing graphs and charts

Struggling with syntax and in need of assistance. I have a basic data set that I want to display as a timeline with two filled lines (Time Series with Rangeslider).

This is the format of my data set:

[{"pm10": 12.1, "pm25": 7.0, "time": "13.08.2018 12:25:09"}, {"pm25": 6.6, "pm10": 11.1, "time": "13.08.2018 12:30:49"}, {"pm10": 12.6, "pm25": 6.2, "time": "13.08.2018 16:59:06"},   {"pm10": 9.2, "pm25": 5.8, "time": "13.08.2018 19:37:01"}, {"pm25": 5.1, "pm10": 8.7, "time": "13.08.2018 19:42:46"},   {"pm10": 7.3, "pm25": 5.5, "time": "13.08.2018 21:42:23"}, {"pm25": 5.1, "pm10": 7.1, "time": "13.08.2018 21:47:56"}, {"pm10": 8.3, "pm25": 5.5, "time": "13.08.2018 21:53:28"}]

I have tried various methods to structure the JSON for proper output but am struggling with:

  • retrieving real-time data (on loading) from an external .JSON file
  • organizing the array so Plotly can present the two lines (pm25 and pm10)

I've dedicated three days to this without success, any guidance would be greatly appreciated.

So far, I have attempted the solutions provided by others and reached this point: https://jsfiddle.net/v15wmeuL/2/

Answer №1

If you need to extract information from an external JSON source, consider utilizing xmlHttpRequests or a similar method.

I have modified your code slightly to exhibit the desired data as two distinct curves:

let curve1 = {
  x: [],
  y: [],
  mode: "lines"
};
let curve2 = {
  x: [],
  y: [],
  mode: "lines"
};
data.forEach(function(value) {
  curve1.x.push(value["time"]);
  curve1.y.push(value["pm25"]);
  curve2.x.push(value["time"]);
  curve2.y.push(value["pm10"]);
});
Plotly.newPlot('AQI', [curve1, curve2]);

Answer №2

For those utilizing JQuery, the following syntax can prove to be quite beneficial:

jQuery.ajax({
method: 'GET',
async: true,
url: '/api-data',
success: function (data) {
    let line1 = {
        x: [],
        y: [],
        mode: "lines"
    };
    let line2 = {
        x: [],
        y: [],
        mode: "lines"
    };
    data.forEach(function(value) {
        line1.x.push(value["time"]);
        line1.y.push(value["pm25"]);
        line2.x.push(value["time"]);
        line2.y.push(value["pm10"]);
    });
    Plotly.newPlot('AirQualityIndex', [line1, line2]);
  }
});

Answer №3

Great news, the plotting functionality is up and running smoothly!

However, I'm still encountering issues with retrieving the data.

Here is my current progress:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
     if (this.readyState == 4 && this.status == 200) {
    var myObj = JSON.parse(this.responseText);
     }
};

 data = xmlhttp.open("GET", 
 "http://192.168.0.170/aqi.json", true);

let trace1 = {
  x: [],
  y: [],
  mode: "lines"
  };
let trace2 = {
  x: [],
  y: [],
  mode: "lines"
  };
data.forEach(function(val) {
 trace1.x.push(val["time"]);
 trace1.y.push(val["pm25"]);
 trace2.x.push(val["time"]);
 trace2.y.push(val["pm10"]);
});
Plotly.newPlot('AQI', [trace1, trace2]);

https://jsfiddle.net/v15wmeuL/14/ for a demonstration of the plotting feature. Keep in mind that Plotly requires a specific date format, so adjustments were made to accommodate the incoming data.

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

Conceal the button briefly when clicked

How can I disable a button on click for a few seconds, show an image during that time, and then hide the image and display the button again? HTML: <input type="submit" value="Submit" onclick="validate();" name="myButton" id="myButton"> <img st ...

Find elements that are not contained within an element with a specific class

Imagine having this HTML snippet: <div class="test"> <div class="class1"> <input type="text" data-required="true"/> </div> <input type="text" data-required="true"/> </div> I'm looking to select ...

JavaScript - changing object into a string (not functioning properly)

Looking to convert a JavaScript object into a string? Here's an example: var obj = {"name": "XXX", "age": "27"}; After doing some research, I found out about JSON.stringify(obj); JSON.stringify(obj); works perfectly when the IE8 modes are set as fo ...

Guide to converting a specific tag into div using Javascript

I am working with some HTML code that includes a div: <div class="myDiv"> <a href="" title="">My link</a> <p>This is a paragraph</p> <script>//This is a script</script> </div> Additionally, I ha ...

Dealing with corrupted bytes of unicode while parsing a JSON string in Python

My script fetches content from a UserVoice site, but unfortunately, UserVoice's data handling capabilities are lacking. To minimize text on the search page, they cut off at around 300 characters and add "..." at the end. The issue here is that they do ...

Is there a method to display the Freshservice app on portal pages specifically for Requesters' view?

Here is what I need: 1. The user will input a subject. 2. Based on the subject, I need to make a call to a third-party REST API (Unfortunately, it is currently blocked by CORS and even JSONP requests are not working). 3. After receiving the response, I w ...

A Guide to Handling Errors while Converting a Map to a Promise in Typescript

I am attempting to capture errors if any of the asynchronous code within my map function fails. It seems to enter the error block but does not log anything, as the error variable remains null. Is there an alternative method for handling errors within map ...

Saving JSON data retrieved from the server into an array in Angular 2

Using a nodejs server to retrieve data from an SQL database has been challenging. I attempted to store the data in taches, which is an array of Tache : getTaches(): Observable<Tache[]> { return this.http.get(this.tachesUrl) .map(response => ...

Utilizing async/await in JavaScript within a class structure

I am facing a dilemma in using the new async/await keywords within the connect method of my JavaScript class. module.exports = class { constructor(url) { if(_.isEmpty(url)) { throw `'url' must be set`; } ...

Remove any null or blank values from a JSON field within a MYSQL array

Within a table, there is a JSON field where arrays containing data are stored. For instance: ["a", "", "c"] ["", "", ""] ["a", "b", "c"] The task is to remove empty values from this field and obtain: ["a", "c"] null ["a", "b", "c"] Afterward, update ...

Refine the table by selecting rows that contain a specific value in the href attribute of the <a> tag, and display the parent row when the child row

I've been working on filtering and searching the table below based on the href value. My code successfully filters the displayed columns in the table, but it fails to work when I search for a string within the href attribute. For instance, if I searc ...

Strategies for capturing POST data sent to a JavaScript webpage

The request is sent from an external source beyond my control xyz.php <form action='https_:_//xyz.com/javascriptFile' method='POST'> <input type='text' name='data' /> </form> to: (My custom f ...

Split and show various JSON values in distinct <span> elements using ReactJS

Within my blogData JSON object, the key tags can contain multiple tag values. I want to display these tags separately inside span tags by iterating through them using the map function. Currently, all the tags are being displayed in a single span tag (show ...

I am looking for information on how to properly handle HTTP errors in Axios when utilizing a blob responseType in VueJs

Using the blob responseType with Axios in my VueJS app allows me to download a document from the server. Everything works fine when the response code is 200, but problems arise when there's an HTTP error. I find it challenging to read the status code ...

Why do identical elements show different scrollHeights when overflowed and how can this discrepancy be resolved?

I am using a plugin that generates a <p> element and continuously fills it with the content from a <textarea>. This plugin positions the <p> directly below the <textarea>, and styles them so that they appear identical in terms of th ...

What is the best method for uploading a JSON file to a React web application and retrieving the file's link?

Is there a way to upload a JSON file to my React application and obtain the link to that file? Our app developer is working on implementing app linking and has requested this functionality. ...

Leveraging Next.js ISR to pass extra information to the getStaticProps function from the getStaticPaths

Inside SingleBlogPost.jsx, the code for generating blog pages by their slug is as follows: export async function getStaticPaths() { const res = await fetch("http://localhost:1337/api/posts"); let { data } = await res.json(); const paths = data.map(( ...

The REST POST controller is notifying that it encountered an error while attempting to read a JSON file. Specifically, the error message states:

I'm currently attempting to conduct an integration test on a REST controller's POST handler. However, I am facing some difficulties in doing so. During the test, I encountered the HttpMessageNotReadableException exception with the message: "Coul ...

The 'SVGResize' or 'onresize' property is not available on the 'SVGProps<SVGSVGElement>' type

Using React with SVG I'm facing an issue with handling the resizing event of an svg element. I have looked into using the SVGResize and onresize events, but encountered compilation errors when trying to implement them: const msg1 = (e: any) => co ...

Here is the process to make a GET request to an API with input parameters using JQuery and JavaScript in an Asp.net view when a particular tag

Seeking assistance in displaying the count of orders on my view using a special tag. I have written a stored procedure in SQL that returns the order count based on the input type. To showcase all types of orders, I have designed multiple boxes on my form. ...