Unable to plot JSON to chartJS - javascript

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.

Related

ChartJs Doughnut parsing datasets

I‘m trying to create a doughnut chart with custom objects as data. I don’t know if it is a bug or am I stupid. 😩
If the type of the chart is „bar“ everything is working as expected but if I change it to doughnut the chart area is empty.
Here is the code for the bar chart:
var myChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
label: '# of Votes',
data: [{vX:12, n:'vx'}, {vX:13, n:'vx2'}],
parsing:{
yAxisKey:'vX',
xAxisKey: 'n'
},
borderWidth: 1
}]
},
options: {
}
});
and that‘s my doughnut:
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [{
label: '# of Votes',
data: [{vX:12, n:'vx'}, {vX:13, n:'vx2'}],
parsing:{
yAxisKey:'vX',
},
borderWidth: 1
}]
},
options: {
}
});
Is parsing not supported for doughnut charts? I can‘t find information about this in the docs.
thanks, Christian
Regarding data structures, the Chart.js documentation says:
For a pie (and doughnut) chart, datasets need to contain an array of data points. The data points should be a number (...)
Therefore, parsing doesn't make sense and is probably not supported. The problem can be solved by mapping your data to labels and data as follows.
var data = [{vX:12, n:'vx'}, {vX:13, n:'vx2'}];
new Chart('myChart', {
type: 'doughnut',
data: {
labels: data.map(v => v.n),
datasets: [{
label: '# of Votes',
data: data.map(v => v.vX),
borderWidth: 1
}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart"></canvas>
At the moment chart.js does not support object notation with parsing for pie/doughnut charts.
There has been a pr for this a few days ago which is merged into the master so as soon as a new version of chart.js releases, anything beyond version 3.5.1 will have this change in it and then you can use your object.
Otherwise you can take the route #uminder suggested and map the data yourself
As mentioned by Christian, It's available since 3.6.0 (2021-10-24, see https://github.com/chartjs/Chart.js/issues/9440) with sth. like this:
options: {
parsing: {
key: "the-label-key',
}
}
ref official doc: https://www.chartjs.org/docs/latest/general/data-structures.html

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.

How to load Json data onto a Charts.js chart

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!

Multiple line labels for chart js

I have this radar chart in chart.js which has 5 labels. The labels are quite long so I want to show them in two lines in HTML but when I use "\n" it doesn't make a new line!
These are my labels:
labels: ["COMMUNICATION \n SKILL ", "PRODUCT AND PROCESS \n KNOWLEDGE "]
As you can see I'm trying to have "communication skill" and "product and process knowledge" both in two lines but it shows them in one line!
What's the correct way to do it?
UPDATE
The labels is in script tag:
var myChart = new Chart(ctx, {
type: 'radar',
data: {
labels: ["COMMUNICATION SKILL ", "PRODUCT AND PROCESS KNOWLEDGE "],
datasets: [{
label: labs,
data: dps,
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
],
borderWidth: 1
},
options: {
maintainAspectRatio: true,
scale: {
ticks:{
beginAtZero: true,
max: 4
}
}
}
});
I believe what you are looking for is answered here:
ChartJS New Lines '\n' in X axis Labels or Displaying More Information Around Chart or Tooltip with ChartJS V2
The solution is to pass a nested array as an input to 'labels' - with each element in the nested array representing a new line of text in your label. So in your case the following should work:
labels: [["COMMUNICATION","SKILL"], ["PRODUCT AND PROCESS","KNOWLEDGE"]]
Just read the docs https://www.chartjs.org/docs/latest/charts/radar.html
you need your dataset to have the property data and that should be an array. The values in the array will correspond with the values in the labels by their index number.
data: {
labels: ['Running', 'Swimming', 'Eating', 'Cycling'],
datasets: [{
data: [20, 10, 4, 2]
}]
}

How do I get a different label for each bar in a bar chart in ChartJS?

I've been working with ChartJS for the last couple of weeks and I'm getting used to it, however, I'm trying to add individual labels to my bars in my barchart and I can't figure it out.
Below is the code I'm using.
var config = {
type : 'bar',
data : {
datasets : [ {
label: numberOfFailures, //This line is the problem
data : failureData,
backgroundColor : colours,
} ],
labels : labels
},
options : {
responsive : true,
legend : {
position : 'bottom'
}
}
};
If I change the word label to labels they don't show up at all, but when it says label they all show up together. What I want is for array element 1 to appear on bar 1, etc.
If your aim is to take the values from an array and have them appear along the bottom of the bar chart so that each array value is the label for a bar then you need to set the data.labels value, not the data.datasets.label value.
For example, this basic chart is taken from the Chart.js documentation for bar chart data structure and shows how to use an array of month names to label the bars. Notice that the label bars go into the data.labels node.
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 80, 81, 56, 55, 40],
}
]
};
If you programmatically create an array with one label for each point of data then it might look something like this:
var chartConfig = {};
for (score = 0; score < maxScore; ++score) {
chartConfig.scoreLabels[score] = score;
chartConfig.scoreData[score] = howManyAchievedScore(score);
}
var data = {
labels: chartConfig.scoreLabels,
datasets: [
{
label: "Number of players who achieved score",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: chartConfig.scoreData,
}
]
};
You don't have to create the labels and data values inside a single object, but it's usually tidier if you can group your chart configuration data into one object so that you can pass it from one function to another with one parameter.
The data.datasets.label value does something different, providing text which appears in the chart legend and in tooltips which appear when you hover over a bar.

Categories