How to load data from Variable in eCharts - javascript

My problem is in displaying data, I cant display it at all.
When I write it like this it works "data: [5, 0, 2, 1, 2, 1, 0, 0, 5]"
But when I use function to load and push data it display nothing. Data in console looks same to me "[5, 0, 2, 1, 2, 1, 0, 0, 5]".
var f = document.getElementById("lineChart");
new Chart(f, {
type: "line",
data: {
labels: ["3:00","6:00", "9:00", "12:00", "15:00", "18:00", "21:00", "24:00"],
datasets: [{
label: "Stress value:",
backgroundColor: "rgba(38, 185, 154, 0.31)",
borderColor: "rgba(38, 185, 154, 0.7)",
pointBorderColor: "rgba(38, 185, 154, 0.7)",
pointBackgroundColor: "rgba(38, 185, 154, 0.7)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointBorderWidth: 1,
data: (function (){
var res = [];
var len = 10;
$.ajax({
dataType:"JSON",
type: 'GET',
url: "https://stressmonitor.smasty.net/api/1.0/day_stress/2017-02-26/?app_id=12345&token=12345"
}).then(function(dataa) {
var i= 0;
while (len--) {
console.log(res);
res.push(dataa.intervals[i].value);
i++;
}
});
return res;
})()
}]
}
})
}

Related

Adding additional data to chart

I am trying to add some data to a chart created with chart.js.
I get "undefined" as an error. How do I add data into this? Looks like a stupid silly newbie error...please bear with me and help. Thanks
var birdsCanvas = document.getElementById("birdsChart");
Chart.defaults.global.defaultFontFamily = "Lato";
Chart.defaults.global.defaultFontSize = 18;
var birdsData = {
labels: ["Spring", "Summer", "Fall", "Winter"],
datasets: [{
//data: [1200, 1700, 800, 200],
data: [5, 10, 3, 9],
backgroundColor: [
"rgba(255, 0, 0, 0.6)",
"rgba(0, 255,200, 0.6)",
"rgba(200, 0, 200, 0.6)",
"rgba(0, 255, 0, 0.6)"
],
borderColor: "rgba(0, 0, 0, 0.8)"
}]
};
var chartOptions = {
startAngle: -Math.PI / 4,
legend: {
position: 'left'
},
animation: {
animateRotate: false
}
};
var polarAreaChart = new Chart(birdsCanvas, {
type: 'polarArea',
data: birdsData,
options: chartOptions
});
//alert ('checking value... birdsData label 1 ' + birdsData.labels[1]);
polarAreaChart.birdsData.datasets.push({
label: 'label2',
backgroundColor: 'rgba(255, 0, 0, 0.6)',
borderColor: 'rgba(255, 0, 0, 0.6)',
data: [9]
});
barChart.update();
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="birdsChart" width="600" height="550"></canvas>
I get TypeError: polarAreaChart.birdsData is undefined .. I just want to add data dynamically through functions when users click on something..
Thanks
You might want to use polarAreaChart.data.datasets.push({ instead of birdsData as there is no bridsData object in the chart object:
var birdsCanvas = document.getElementById("birdsChart");
Chart.defaults.global.defaultFontFamily = "Lato";
Chart.defaults.global.defaultFontSize = 18;
var birdsData = {
labels: ["Spring", "Summer", "Fall", "Winter"],
datasets: [{
//data: [1200, 1700, 800, 200],
data: [5, 10, 3, 9],
backgroundColor: [
"rgba(255, 0, 0, 0.6)",
"rgba(0, 255,200, 0.6)",
"rgba(200, 0, 200, 0.6)",
"rgba(0, 255, 0, 0.6)"
],
borderColor: "rgba(0, 0, 0, 0.8)"
}]
};
var chartOptions = {
startAngle: -Math.PI / 4,
legend: {
position: 'left'
},
animation: {
animateRotate: false
}
};
var polarAreaChart = new Chart(birdsCanvas, {
type: 'polarArea',
data: birdsData,
options: chartOptions
});
//alert ('checking value... birdsData label 1 ' + birdsData.labels[1]);
polarAreaChart.data.datasets.push({
label: 'label2',
backgroundColor: 'rgba(255, 0, 0, 0.6)',
borderColor: 'rgba(255, 0, 0, 0.6)',
data: [9]
});
polarAreaChart.update();
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="birdsChart" width="400" height="400"></canvas>

Draw line chart using chart.js with ajax

I'm tring to get Line Chart using Chart.js with ajax json data.
Basically It is ok using custom data eg. [176,617,930,606,649,0,0,0].
But I can't able to get the chart with ajax json data if I try like the below.
My JSON Data is
{'pvideo':[ {'DDATE':"2017-01","TOCDDB_VALUE":"DENY","CNT":"0"}, {'DDATE':"2017-01","TOCDDB_VALUE":"CRREQUEST","CNT":"176"}, {'DDATE':"2017-01","TOCDDB_VALUE":"NOCR","CNT":"0"}, {'DDATE':"2017-02","TOCDDB_VALUE":"DENY","CNT":"0"}, {'DDATE':"2017-02","TOCDDB_VALUE":"CRREQUEST","CNT":"617"}, {'DDATE':"2017-02","TOCDDB_VALUE":"NOCR","CNT":"0"}, {'DDATE':"2017-03","TOCDDB_VALUE":"DENY","CNT":"0"}, {'DDATE':"2017-03","TOCDDB_VALUE":"CRREQUEST","CNT":"930"}, {'DDATE':"2017-03","TOCDDB_VALUE":"NOCR","CNT":"0"}, {'DDATE':"2017-01","TOCDDB_VALUE":"SREG","CNT":"247"}, {'DDATE':"2017-02","TOCDDB_VALUE":"SREG","CNT":"94"}, {'DDATE':"2017-03","TOCDDB_VALUE":"SREG","CNT":"76"} ], ptrights:[ {'DDATE':"2017-01","TOCDDB_VALUE":"DENY","CNT":"0"}, {'DDATE':"2017-01","TOCDDB_VALUE":"CRREQUEST","CNT":"27"}, {'DDATE':"2017-01","TOCDDB_VALUE":"NOCR","CNT":"10"}, {'DDATE':"2017-02","TOCDDB_VALUE":"DENY","CNT":"3"}, {'DDATE':"2017-02","TOCDDB_VALUE":"CRREQUEST","CNT":"10"}, {'DDATE':"2017-02","TOCDDB_VALUE":"NOCR","CNT":"23"}, {'DDATE':"2017-03","TOCDDB_VALUE":"DENY","CNT":"0"}, {'DDATE':"2017-03","TOCDDB_VALUE":"CRREQUEST","CNT":"32"}, {'DDATE':"2017-03","TOCDDB_VALUE":"NOCR","CNT":"11"}]}
And code is
var crcnt = [];
var crcnt2 = [176,617,930,606,649,0,0,0];
var nocrcnt = [];
var denycnt = [];
$.getJSON(url, function(data) {
// I use lodash.js for _.filter and ._map
var crlist = _.filter(data.pvideo, function(o) { return o.TOCDDB_VALUE == 'CRREQUEST' });
var nocrlist = _.filter(data.pvideo, function(o) { return o.TOCDDB_VALUE == 'NOCR' });
var denylist = _.filter(data.pvideo, function(o) { return o.TOCDDB_VALUE == 'DENY' });
var crcnt = _.map(crlist, "CNT");
var nocrcnt = _.map(nocrlist, "CNT");
var denycnt = _.map(denylist, "CNT");});
var canvas1 = new chart(doucment.getElementByID("canvas1"), {
type: 'line',
data: {
labels: ["Jan", "Feb", "Mar","Apr", "May", "Jun", "Jul", "Aug"],
datasets: [{
label: "CRREQUEST",
backgroundColor: "rgba(255, 99, 00, 0.31)",
borderColor: "rgba(255, 99, 204, 0.7)",
pointBorderColor: "rgba(255, 99, 99, 0.7)",
pointBackgroundColor: "rgba(255, 33, 99, 0.7)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(220,220,220,1)",
data: crcnt
}, {
label: "NOCR",
backgroundColor: "rgba(204, 255, 255, 0.70)",
borderColor: "rgba(99, 255, 255, 0.70)",
pointBorderColor: "rgba(3, 88, 106, 0.70)",
pointBackgroundColor: "rgba(0, 33, 255, 0.70)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(151,187,205,1)",
pointBorderWidth: 1,
data: nocrcnt
}, {
label: "DENY",
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(0,0,30,1)",
pointBorderColor: "rgba(3, 88, 106, 0.70)",
pointBackgroundColor: "rgba(3, 88, 106, 0.70)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(151,187,205,1)",
pointBorderWidth: 1,
data: denycnt
}]});
I checked that custom data and json data is same by chrome console.
Console Capture

Chart JS add max value to legend

I'm new in Chart JS and I'm trying to add the maximum values for each dataset inside the legend. I've tried using legendCallback :
HTML:
<canvas id="lineChart"></canvas>
Javascript:
var ctx = document.getElementById("lineChart");
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['1','2','3','4','5','6','7','8','9','10'],
datasets: [{
label: "Max",
backgroundColor: "rgba(235, 70, 70, 0.31)",
borderColor: "rgba(231, 25, 25, 0.7)",
pointBorderColor: "rgba(231, 25, 25, 0.7)",
pointBackgroundColor: "rgba(231, 25, 25, 0.7)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointBorderWidth: 1,
data: [31, 74, 6, 39, 20, 85, 7, 80, 35, 70]
}, {
label: "Avg",
backgroundColor: "rgba(255, 255, 111, 0.3)",
borderColor: "rgba(255, 255, 50, 0.70)",
pointBorderColor: "rgba(255, 255, 50, 0.70)",
pointBackgroundColor: "rgba(255, 255, 50, 0.70)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(151,187,205,1)",
pointBorderWidth: 1,
data: [82, 23, 66, 9, 99, 4, 2, 25, 67, 20]
},
{
label: "Min",
backgroundColor: "rgba(90, 189, 90, 0.3)",
borderColor: "rgba(50, 173, 50, 0.70)",
pointBorderColor: "rgba(50, 173, 50, 0.70)",
pointBackgroundColor: "rgba(50, 173, 50, 0.70)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(151,187,205,1)",
pointBorderWidth: 1,
data: [30, 46, 60, 29, 79, 54, 23, 25, 47, 10]
}]
},
options: {
legend: {
display: true,
position: 'bottom'
},
legendCallback: function(chart) {
return 'a';
},
scales: {
xAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}]
}
}
});
but the displayed legend didn't changed. I've searched for some answers and I also tried using: lineChart.generateLegend(); but still no result.
It is possible to add the maximum value for each dataset inside legend?
Thanks in advance!
Yes, it is possible to show the max value for each dataset inside the legend. You can use the legend.labels.generateLabels config property to do this.
This property allows you to define your own function that generates the legend labels. To add the max, we simply iterate through each dataset's data array, find the max, and build it into the label string.
Here is an example configuration. The magic happens when we set the text property in the return.
legend: {
display: true,
position: 'bottom',
labels: {
generateLabels: function(chart) {
var data = chart.data;
return Chart.helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {
return {
text: dataset.label + " (Max Value: " + Chart.helpers.max(dataset.data).toLocaleString() + ")",
fillStyle: (!Chart.helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
hidden: !chart.isDatasetVisible(i),
lineCap: dataset.borderCapStyle,
lineDash: dataset.borderDash,
lineDashOffset: dataset.borderDashOffset,
lineJoin: dataset.borderJoinStyle,
lineWidth: dataset.borderWidth,
strokeStyle: dataset.borderColor,
pointStyle: dataset.pointStyle,
// Below is extra data used for toggling the datasets
datasetIndex: i
};
}, this) : [];
},
},
},
I also created a codepen to demonstrate this.

Update the Chartjs push data with ajax

This is the code that I have created to render chart with Chart.js library:
$(document).ready(function(){
$.ajax({
url : "data.php",
type : "JSON",
success : function(data){
var lung = data.length;
console.log(data);
var timestamp_utc = [];
var temperature = [];
for(var i in data) {
timestamp_utc.push(data[i].timestamp_utc);
temperature.push(data[i].temperature);
}
var config_temp = {
labels: timestamp_utc.slice(lung-10, lung),
datasets: [
{
label: "temperature",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(0, 169, 252, 0.75)",
borderColor: "rgba(0, 169, 252, 1)",
pointRadius: "5",
pointColor: "rgba(0, 169, 252, 1)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "rgba(0, 169, 252, 1)",
pointHoverBorderColor: "rgba(0, 169, 252, 1)",
data: temperature.slice(lung-10, lung)
}]
};
var ctx_temp = $("#mycanvas");
var LineGraph_temp = new Chart(ctx_temp, {
type: 'line',
data: config_temp
});
},
error : function(data) {
}
});
});
I want to update graph every 15 minutes.
how can I do that?
You can use setInterval method to execute the code which renders the chart with updated data.
var pollInterval = 15000; //change this value as needed
function renderChart() {
// put your existing code to render the chart here
}
$(function () {
window.setInterval(renderChart, pollInterval);
});

Plotting on charts js more than one dataset

I have the following json:
[
{"periodo":"0","mes":"7","anio":"2015","montoIngreso":0,"monedaIngreso":"0","identifierIngreso":null,"montoGasto":0,"monedaGasto":"0","identifierGasto":null,"balance":0",
{"periodo":"1","mes":"8","anio":"2015","montoIngreso":0,"monedaIngreso":"0","identifierIngreso":null,"montoGasto":0,"monedaGasto":"0","identifierGasto":null,"balance":0},
{"periodo":"2","mes":"9","anio":"2015","montoIngreso":0,"monedaIngreso":"0","identifierIngreso":null,"montoGasto":0,"monedaGasto":"0","identifierGasto":null,"balance":0},
{"periodo":"3","mes":"10","anio":"2015","montoIngreso":0,"monedaIngreso":"0","identifierIngreso":null,"montoGasto":0,"monedaGasto":"0","identifierGasto":null,"balance":0},
{"periodo":"4","mes":"11","anio":"2015","montoIngreso":0,"monedaIngreso":"0","identifierIngreso":null,"montoGasto":0,"monedaGasto":"0","identifierGasto":null,"balance":0},
{"periodo":"5","mes":"12","anio":"2015","montoIngreso":0,"monedaIngreso":"0","identifierIngreso":null,"montoGasto":0,"monedaGasto":"0","identifierGasto":null,"balance":0},
{"periodo":"6","mes":"1","anio":"2016","montoIngreso":0,"monedaIngreso":"0","identifierIngreso":null,"montoGasto":0,"monedaGasto":"0","identifierGasto":null,"balance":0},
{"periodo":"7","mes":"2","anio":"2016","montoIngreso":0,"monedaIngreso":"0","identifierIngreso":null,"montoGasto":0,"monedaGasto":"0","identifierGasto":null,"balance":0},
{"periodo":"8","mes":"3","anio":"2016","montoIngreso":0,"monedaIngreso":"0","identifierIngreso":null,"montoGasto":0,"monedaGasto":"0","identifierGasto":null,"balance":0},
{"periodo":"9","mes":"4","anio":"2016","montoIngreso":0,"monedaIngreso":"0","identifierIngreso":null,"montoGasto":0,"monedaGasto":"0","identifierGasto":null,"balance":0},
{"periodo":"10","mes":"5","anio":"2016","montoIngreso":0,"monedaIngreso":"0","identifierIngreso":null,"montoGasto":0,"monedaGasto":"0","identifierGasto":null,"balance":0},
{"periodo":"11","mes":"6","anio":"2016","montoIngreso":3833.874,"monedaIngreso":"1","identifierIngreso":"ARS","montoGasto":175.56,"monedaGasto":"1","identifierGasto":"ARS","balance":3658.314},
{"periodo":"11","mes":"6","anio":"2016","montoIngreso":3833.874,"monedaIngreso":"1","identifierIngreso":"ARS","montoGasto":"460810","monedaGasto":"2","identifierGasto":"USD","balance":-456976.126},
{"periodo":"11","mes":"6","anio":"2016","montoIngreso":3833.874,"monedaIngreso":"1","identifierIngreso":"ARS","montoGasto":190.4448,"monedaGasto":"3","identifierGasto":"UYU","balance":3643.4292},
{"periodo":"11","mes":"6","anio":"2016","montoIngreso":"5000","monedaIngreso":"2","identifierIngreso":"USD","montoGasto":175.56,"monedaGasto":"1","identifierGasto":"ARS","balance":4824.44},
{"periodo":"11","mes":"6","anio":"2016","montoIngreso":"5000","monedaIngreso":"2","identifierIngreso":"USD","montoGasto":"460810","monedaGasto":"2","identifierGasto":"USD","balance":-455810},
{"periodo":"11","mes":"6","anio":"2016","montoIngreso":"5000","monedaIngreso":"2","identifierIngreso":"USD","montoGasto":190.4448,"monedaGasto":"3","identifierGasto":"UYU","balance":4809.5552},
{"periodo":"12","mes":"7","anio":"2016","montoIngreso":219.318,"monedaIngreso":"1","identifierIngreso":"ARS","montoGasto":15.444,"monedaGasto":"1","identifierGasto":"ARS","balance":203.874},
{"periodo":"12","mes":"7","anio":"2016","montoIngreso":219.318,"monedaIngreso":"1","identifierIngreso":"ARS","montoGasto":"105002","monedaGasto":"2","identifierGasto":"USD","balance":-104782.682},
{"periodo":"12","mes":"7","anio":"2016","montoIngreso":"324342","monedaIngreso":"2","identifierIngreso":"USD","montoGasto":15.444,"monedaGasto":"1","identifierGasto":"ARS","balance":324326.556},
{"periodo":"12","mes":"7","anio":"2016","montoIngreso":"324342","monedaIngreso":"2","identifierIngreso":"USD","montoGasto":"105002","monedaGasto":"2","identifierGasto":"USD","balance":219340}]
And i have a var with the labels:
["2015-7", "2015-8", "2015-9", "2015-10", "2015-11", "2015-12", "2016-1", "2016-2", "2016-3", "2016-4", "2016-5", "2016-6", "2016-7"]
From the first json, there supposed to be three datasets "montoIngreso" "montoGasto" and "balance"
The problem is that for some of the labels, i have two values on the json, for instance
anio:2016 mes:7 have 4 records so i need to add each of them to form 3 unique datasets
how can i do this?
Thanks!
Ok its not fancy but:
var valoresIngresos = new Array(labels.length).fill(0);
var valoresGastos = new Array(labels.length).fill(0);
var valoresBalance = new Array(labels.length).fill(0);
for(var i=0;i<labels.length;i++) {
var fuentes = dataSource.filter(source=>(source.anio+"-"+source.mes) == labels[i]);
for(var j=0;j<fuentes.length;j++) {
valoresIngresos[i] = valoresIngresos[i]+parseFloat(fuentes[j].montoIngreso);
valoresGastos[i] = valoresGastos[i]+parseFloat(fuentes[j].montoGasto);
valoresBalance[i] = valoresBalance[i]+parseFloat(fuentes[j].balance);
}
}
var ingresosDataset = {
label: "Ingresos",
data:valoresIngresos,
backgroundColor: "rgba(38, 185, 154, 0.31)",
borderColor: "rgba(38, 185, 154, 0.7)",
pointBorderColor: "rgba(38, 185, 154, 0.7)",
pointBackgroundColor: "rgba(38, 185, 154, 0.7)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointBorderWidth: 1,
};
datasets.push(ingresosDataset);

Categories