How to load Json data onto a Charts.js chart - javascript

I would like to display the data variable "temp" which is listed by ID under (.list) on the following Json (http://api.openweathermap.org/data/2.5/forecast?lat=53.4808&lon=2.2426&appid=4ce23fd03d1558816c3ef6efb6a5ec30&units=metric) as an x axis variable on this chart:
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
// Configuration options go here
options: {}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<canvas id="myChart"></canvas>
The chart currently functions alone without the Json data. How would I import this specified data so that it can replace the "data: [0, 10, 5, 2, 20, 30, 45]" variables?

Assuming your main stumbling block is retrieving the data from the API, all you need are three steps:
Making a network request to the URL you posted, usually done using fetch. This asks the openweathermap website to send you some data.
const response = await fetch('http://api.openweathermap.org/data/2.5/forecast?lat=53.4808&lon=2.2426&appid=4ce23fd03d1558816c3ef6efb6a5ec30&units=metric');
This will give you an object of type Response, which is not what you want since it includes HTTP headers etc. which you have no use for. You want the JSON data sent as part of the response.
Extracting the JSON
const data = await response.json()
Parsing the JSON variable for the temp values
const chartData = data.list.map((object) => object.main.temp)
Explanation: The JSON object returned by the API contains a "list" array that itself contains a "main" attribute, that finally contains the temp you're looking for. "json.list" access the list, the map is taking each object and creating a new array (I believe) containing the "temp" value inside the "main" object.
Lmk if that wasn't clear!

Related

Connecting API data array to chartjs in django

I am trying to create a chart using chartjs and this chart is displaying API data(Stock Data). I have made the API successfully and make the data wanted in the form of an array inorder to put it in the chart. When I define the API data array as a variable and use the variable in the chart data it doesn't display anything:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
<script>
const ctx = document.getElementById('myChart');
let y=new Array();
let theapi = fetch('api_src')
.then(response => response.json())
.then(data => {
const thewanted = Object.values(data)[1]
for (const [key, value] of Object.entries(thewanted)) {
y.push(key);
}
console.log(y)
})
new Chart(ctx, {
type: 'line',
data: {
labels: y,
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
}]
}
,
options: {
scales: {
y: {
beginAtZero: true
}}}});
</script>
if you look at the labels in the chart you will find that I have used the variable as the value of the labels but it doesn't work and whan I console.log the variable I find that it contains the values that I want.
Note: When I closed the pc and opened it again after time I found that it worked but when I refreshed the page or restarted the server it doesn't work
update: the chart data is shown only when I zoom the page in or out and other than that it shows a blank chart.

Chart.js plot live data

I am receiving live stocks data from a websocket and pushing the data into an array. I want to plot a line graph with live data.
let aaplArr = new Array(); // creating an empty array
let rowData = x.Data[0].RowData[4]; // this the data received from the websocket
aaplArr.push(rowData); // pushing data into array
let graphPoints = (arr) => {
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
data: arr,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
],
borderWidth: 1
}]
},
});
I want to call the graphPoints(aaplArr) function. I'm not getting the data on the graph. How do I get around this?
I have used HTML canvas for the graph and need to keep reloading the graph for every new value in the array.
You are trying to create the chart again everytime which is inneficient and afaik not even possible, if I am correct chart.js throws an error that the canvas is already in use, to achieve what you want you need to create the chart once outside the function, store in in a variable and then in your graphPoints function you call myChart.data.datasets[0].data.push(...arr) after that you can call the update method on chart.js like so: mychart.update() this will make chart.js update and render all the new values.

Passing data to a chart javascript object and array

What is the best approach to display the data in a chart?
To begin, my application has an empty array that receives objects.
// location where the users are storage
let usersList = [];
// these are the information from an user
const newUser = {
name:`${user.name.first} ${user.name.last}`,
social: Math.floor(Math.random() * 1000 )
}
So, by the end of my code, I have the chart, everything is working but with dummy data.
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], // should get the usersList.name
datasets: [{
label: ' Views per channel ',
data: [12, 10, 3, 5, 2, 3], // // should get the usersList.social
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
Ideally, I would need to change the labels to have the name of each user, and the data to have the social of each user. My initial thought was a for loop, but I remember that ES6 has array destructuring.
I am not sure how to approach the problem, do you have any insight?
Thank you very much.
You can use the Array.map() method on the usersList to create the arrays that contain the desired attributes of the users.
Your code would have to be changed as follows:
data: {
labels: usersList.map(u => u.name),
datasets: [{
label: ' Views per channel ',
data: usersList.map(u => u.social),
borderWidth: 1
}]
}

How to use JSON data as chartjs data?

In my controller I have an Action method that will find all questions in a table called Questions, and the answers for each question. This Action is of type ContentResult that will return a result serialized in Json format.
public ContentResult GetData()
{
foreach (var question in datalistQuestions)
{
//queries
}
return Content(JsonConvert.SerializeObject(questionlist), "application/json");
}
This is returning:
[{"countAgree":1,"countSomewhatAgree":0,"countDisagree":1},
{"countAgree":0,"countSomewhatAgree":1,"countDisagree":1},
{"countAgree":0,"countSomewhatAgree":1,"countDisagree":1}]
I want to display a chart for each question. The dynamic charts are created when im using hard coded dataset. JSFIDDLE
But how do I fetch this json data and use it as the dataset for my charts?
Take your data as Objects. Consider Keys are Labels and Values in objects are Points. then draw the graph. using this code.
data = {"countAgree":1,"countSomewhatAgree":0,"countDisagree":1,
"countAgree":0,"countSomewhatAgree":1,"countDisagree":1,
"countAgree":0,"countSomewhatAgree":1,"countDisagree":1};
const CHART = document.getElementById('lineChart');
var lineChart = new Chart(CHART, {
type: 'line',
data: {
labels: Object.keys(data),
datasets: [{
label: 'My first dataset',
fill: false,
lineTension: 0,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJointStyle: 'miter',
data: Object.values(data)
}]
}
})

Unable to plot JSON to chartJS

I'm trying to plot a dataset into a chartJS line chart:
This is my data:
[{"close":0.00786609},{"close":0.00784},{"close":0.00784},
{"close":0.00780507},{"close":0.007816},{"close":0.00781599},
{"close":0.00780166},{"close":0.00778403},{"close":0.00782001},
{"close":0.0078},{"close":0.00778},{"close":0.007799},
{"close":0.00775057},{"close":0.0077688},{"close":0.00775001}]
This is my code:
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
datasets: [{
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: <%= JSON.stringify(prices) %>,
}]
},
// Configuration options go here
options: {}
});
How can I fix this?
You have configured your chart to be of type "line". The documentation for this type specifies that a dataset's data can be an Array of Numbers or an Array of Points, where a Point is an Object with a x property and a y property.
Your data is a JSON stringified Array of objects, each with a close property.
You need to map your prices Array into an Array of Numbers. In JavaScript, this could be done as:
prices.map(function (price) {
return price.close;
});
I have created a fiddle as an example.

Categories