How to make range of labels in javascript graph - javascript

I want to make range of labels like 90 to 1. How I can do it insted of typeing '90',89','88',....
Please help. Should I use ForEach loop or something else or there is some function like range(1-90)?
$.getJSON("/administration/statistics/datasource/grafpobrojuuplata90dana.json", function (data) {
zbrojevi = data.zbrojevi;
var result = Object.values(zbrojevi);
console.log(result);
var ctx = document.getElementById('grafpobrojuuplata90dana').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
axisX:{
scaleBreaks: {
autoCalculate: true
}
},
toolTip: {
shared: true
},
// The data for our dataset
data: {
labels: ['90','89','88','87','86','85','84','83','82','81','80','79','78','77','76','75','74','73','72','71','70','69','68','67','66','65','64','63','62','61','60','59','58','57','56','55','54','53','52','51','50','49','48','47','46','45','44','43','42','41','40','39','38','37','36','35','34','33','32','31','30','29', '28', '27', '26', '25', '24', '23','22','21','20','19','18','17','16','15','14','13','12','11','10','9','8','7','6','5','4','3','2','1','danas'],
datasets: [{
label: 'Graf po broju uplata 90 dana',
backgroundColor: 'rgb(51, 153, 255)',
borderColor: 'rgb(0, 0, 255)',
data: result
}]
},
});
});

var label = [];
for (var j = 90; j >= 1; j--) {
label.push(j);
}
console.log(label);

Related

How can my Chart.js just update when data in SQL change?

I build a web app in MVC using SignalR to update real-time data. I can display my chart with real-time data from SQL but it just updates by the time set in setInterval. But now I want my chart to just update when my data in SQL SERVER changes. I have tried many ways but it's not correct. Can you help me with the algorithm? Thank you.
Here is my code :
<!--Chart-->
<script>
var ctx = document.getElementById("percent-chart2");
var colorarray = ['#00b5e9', '#fa4251', '#006400'];
var pre_vals = 0;
//
var myVar = setInterval(GetValue, 1000);
function GetValue() {
var val1 = parseFloat(document.getElementById("tblValue").innerHTML);
var val2 = parseFloat(document.getElementById("tblValue1").innerHTML);
var vals = [val1, val2, 2000];
return vals;
}
if (ctx) {
ctx.height = 209;
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [
{
label: "My First dataset",
//data: [GetValue, GetValue, GetValue],
data: GetValue(),
backgroundColor: [
'#00b5e9',
'#fa4251',
'#006400'
],
hoverBackgroundColor: [
'#00b5e9',
'#fa4251',
'#006400'
],
borderWidth: [
0, 0, 0
],
hoverBorderColor: [
'transparent',
'transparent',
'transparent'
]
}
],
labels: [
'STATION 1',
'STATION 2',
'STATION 3'
]
},
options: {
maintainAspectRatio: false,
responsive: true,
cutoutPercentage: 57,
animation: {
animateScale: true,
animateRotate: true
},
legend: {
display: false,
position: 'bottom',
labels: {
fontSize: 14,
fontFamily: "Poppins,sans-serif"
}
},
tooltips: {
titleFontFamily: "Poppins",
xPadding: 15,
yPadding: 10,
caretPadding: 0,
bodyFontSize: 16,
}
}
});
}
function UpdateChart(datachart, data, color) {
datachart.data.datasets.pop();
datachart.data.datasets.push({
data: data,
backgroundColor: color,
hoverBackgroundColor: color
});
datachart.update();
}
setInterval(function () {
const my_val = GetValue();
//var updatedata = [my_val, my_val, 2000];
var updatedata = my_val;
UpdateChart(myChart, updatedata, colorarray);
}, 10000);
</script>
The way I handle this is by adding a client call with the dataset after the database update has completed. This way you only update when that update is called.
Here is a rough example off the top of my head:
public void UpdateDB(int updatedData)
{
//DB work to commit the updatedData
....
//Query your dataset into an serialized updatedDataset
....
//Call a method to create an array (updatedColors) of colors based on the the Count of updatedDataset
....
//Send data to client(s)
Clients.All.yourclientfunction(updatedDataset, updatedColors);
}

Passing parameters to linechart angular typescript

I want to pass a parameter to chart line based to json iput s data1 instead of var labeltabmles = ['Redddd', 'Blue', 'Yellow', 'Green'];
var datalabel = [1240, 190, 30, 545];
I did the algorithme below in order to get the values of count on variable listcount and get the values of type on variable listtype to configure parameter labels and data of line chart configuration from json file inputs using the code below :
listcount = [];
listtype = [];
......
ngOnInit(): void {
var data1 = [{
"type": "MATH",
"count": 55
}, {
"type": "ENGLISH",
"count": 22
},
{
"type": "SCINETIST",
"count": 18
}];
for (var key in data1) {
var typeelement = data1[key]["type"];
var countelemtn = data1[key]["count"];
this.listtype.push(typeelement);
this.listcount.push(countelemtn);
console.log(this.listcount);
console.log(this.listtype);
}
console.log(this.listcount);
console.log(this.listtype);
var labeltabmles = ['Redddd', 'Blue', 'Yellow', 'Green'];
var datalabel = [1240, 190, 30, 545];
const myChart1 = new Chart("myChartline", {
type: 'line',
data: {
labels: labeltabmles,
datasets: [{
label: '# of Votes',
data: datalabel,
backgroundColor: "#007ee7",
borderColor: "#007ee7",
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
i want to configure the var labeltabmles = ['Redddd', 'Blue', 'Yellow', 'Green'];
var datalabel = [1240, 190, 30, 545]; using the variables listcount , listtype
where the result of this two array are following the code enter image description here
i need your help to pass listcount and listtype as paramter to datalabel and data of the chart
i tried but the apped didnt happen the this.listype and this.listcount still empty;
var labeltabmles = this.listcount ;
var datalabel = this.listype;
Thanks for your support and help
i find the solution by :
-using the TYPELIST: any = []; COUNTLIST: any = [];
-and update the variable used on push function on the for iteration
for (var key in data1) {
var typeelement = this.contentype[key]["type"];
var countelemtn = this.contentype[key]["count"];
this.TYPELIST.push(typeelement);
this.COUNTLIST.push(countelemtn);
}
const myChart1 = new Chart("myChartline", {
type: 'line',
data: {
labels: this.TYPELIST,
datasets: [{
label: '# of Votes',
data: this.COUNTLIST,
backgroundColor: "#007ee7",
borderColor: "#007ee7",
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});

How to use a Data Array within a Chart JS dataset?

I have the following JSON, that I want to insert a chart using Chart JS:
{"Results":[{"Data":"25/02/2021","Valor":18},{"Data":"24/02/2021","Valor":2993},{"Data":"23/02/2021","Valor":1936},{"Data":"22/02/2021","Valor":1844},{"Data":"21/02/2021","Valor":1114},{"Data":"20/02/2021","Valor":1060},{"Data":"19/02/2021","Valor":1134}]}
And I created a function to load this JSON into an Array:
function ShowData(jsonObj) {
var bases = jsonObj['Results'];
var Date = [];
var Val = [];
for (var i = bases.length-1; i >= 0; i--) {
Date.push([bases[i].Data]);
Val.push([bases[i].Valor]);
}
}
When I load this Array into the Chart, As below:
var chartGraph = new Chart(ctx,{
type:'line',
data:{
labels: Date,
datasets: [
{
label: "Lbl Name",
data: Val,
borderWidth: 6,
borderColor: 'rgba(77,166,253, 0.85)',
backgroundColor: 'transparent'
}
]
},
options: {
title: {
display: true,
fontSize: 20,
text: 'Chart Name'
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#666'
}
}
}
})
No information on "datasets" appears to me, only the "label", what is the mistake I am making?
Graphic Image
Try to split series and data, something like:
function splitData(type) {
return json.Results.map(v => v[type]);
}
// your Chart.js config
data: {
labels: splitData('Date'),
datasets: [
{
// ...otherProps,
data: splitData('Valor')
}
]
}
You cant use Date as variable name since its a build in class. Also from my testing couldnt reference the vars inside the function. But the real problem with your code is that you push an array to the val array. This made it an array containing arrays. This is not supported. If you change your code to the sample below it will work
let date = [];
let val = [];
function ShowData(jsonObj) {
var bases = jsonObj['Results'];
date = [];
val = [];
for (var i = bases.length-1; i >= 0; i--) {
date.push(bases[i].Data);
val.push(bases[i].Valor);
}
}
var chartGraph = new Chart(ctx,{
type:'line',
data:{
labels: Date,
datasets: [
{
label: "Lbl Name",
data: Val,
borderWidth: 6,
borderColor: 'rgba(77,166,253, 0.85)',
backgroundColor: 'transparent'
}
]
},
options: {
title: {
display: true,
fontSize: 20,
text: 'Chart Name'
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#666'
}
}
}
})

Charts Js Stacked Bar Graph displays no values?

I have a javascript map like this..
var Severity = {
3M:[0, 3, 1, 0, 0],
5T:[0, 0, 1, 0, 0],
6S:[0, 0, 2, 0, 0]
}
And a JS function to call Stacked Chart Bar. Here I have a created a JS function which takes id and a map from jsp page. Map structure is same as above defined. I want to display graph where in x axis the data is the keys in map and in y axes is the stacked up data of 5 elements.
function StackedBar(id,Severity) {
var label = Object.keys(Severity); // getting the labels
var Critical = [];
var High = [];
var Medium = [];
var Low = [];
var Others = [];
for(let i=0;i<label.length;i++){ //assigning the data to arrays created
Critical.push(Severity[label[i]][0]);
High.push(Severity[label[i]][1]);
Medium.push(Severity[label[i]][2]);
Low.push(Severity[label[i]][3]);
Others.push(Severity[label[i]][4]);
}
var ctxL = document.getElementById(id).getContext('2d'); //id from the html canvas
var chart = new Chart(ctxL, {
type: 'bar',
data: {
labels: label,
datasets: [
{
label: 'Critical',
data: Critical,
backgroundColor: '#aa000e'
},
{
label: 'High',
data: High,
backgroundColor: '#e65905'
},
{
label: 'Medium',
data: Medium,
backgroundColor: '#e00ce6'
},
{
label: 'Low',
data: Low,
backgroundColor: '#b8ab16'
},
{
label: 'Others',
data: Others,
backgroundColor: '#00aaaa'
}
]
},
options: {
responsive: true,
legend: {
position: 'right'
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
}
Here graph displays and i get label in x axes...but graph values doesn't show and i get following error..
Html
<canvas id="overall"></canvas>
<script>StackedBar('overall',Overall);</script>
I wanted to know what went wrong and want me to help fix this issue...
I put the above together into one file and it works (although I had to change "Overall" to "Severity" in the call). So I'd expect that something you are using might not match your example above.
The version I used:
<html>
<body>
<canvas id="overall"></canvas>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script>
var Severity = {
"3M": [0, 3, 1, 0, 0],
"5T": [0, 0, 1, 0, 0],
"6S": [0, 0, 2, 0, 0]
};
</script>
<script>
function StackedBar(id, Severity) {
var label = Object.keys(Severity); // getting the labels
var Critical = [];
var High = [];
var Medium = [];
var Low = [];
var Others = [];
for (let i = 0; i < label.length; i++) { //assigning the data to arrays created
Critical.push(Severity[label[i]][0]);
High.push(Severity[label[i]][1]);
Medium.push(Severity[label[i]][2]);
Low.push(Severity[label[i]][3]);
Others.push(Severity[label[i]][4]);
}
var ctxL = document.getElementById(id).getContext('2d'); //id from the html canvas
var chart = new Chart(ctxL, {
type: 'bar',
data: {
labels: label,
datasets: [
{
label: 'Critical',
data: Critical,
backgroundColor: '#aa000e'
},
{
label: 'High',
data: High,
backgroundColor: '#e65905'
},
{
label: 'Medium',
data: Medium,
backgroundColor: '#e00ce6'
},
{
label: 'Low',
data: Low,
backgroundColor: '#b8ab16'
},
{
label: 'Others',
data: Others,
backgroundColor: '#00aaaa'
}
]
},
options: {
responsive: true,
legend: {
position: 'right'
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
}
</script>
<script>StackedBar('overall', Severity);</script>
</html>

Chart JS - Line chart with days in x-axis

I need to draw chart with the x-axis to be in day with 12.00 AM. It is using quite alot of point
This is my desire output
But this is the output I am getting:
I am getting this weird "Object object" in the x-axis
//I have truncated the stats as it exceeded the max length in SO
let response = '{"stats":[ { "time":"2018-10-24 13:30:02", "occupation":"54", "liveness":"78", "efficiency":"48", "pms":"up" }, { "time":"2018-10-24 13:45:02", "occupation":"55", "liveness":"78", "efficiency":"50", "pms":"up" }, { "time":"2018-10-24 14:00:01", "occupation":"56", "liveness":"76", "efficiency":"51", "pms":"up" }, { "time":"2018-10-24 14:15:02", "occupation":"56", "liveness":"77", "efficiency":"52", "pms":"up" }, { "time":"2018-10-24 14:30:01", "occupation":"56", "liveness":"78", "efficiency":"53", "pms":"up" }, { "time":"2018-10-24 14:45:01", "occupation":"57", "liveness":"79", "efficiency":"56", "pms":"up" }, { "time":"2018-10-24 15:00:02", "occupation":"57", "liveness":"79", "efficiency":"56", "pms":"up" }]}';
let parsedResponse = ($.parseJSON(response));
let stats = parsedResponse.stats;
let arrayDays = [];
$.each(parsedResponse.days, function(key, value) {
arrayDays.push(moment(value).toDate());
});
let statLength = stats.length;
let occupation = [];
let liveness = [];
let efficiency = [];
let labels = [];
parsedResponse = undefined;
let dataDateTime = '';
let dataDateTimeFormat = 'MMM DD HH:mm A';
for(let index = 0; index < statLength; index++) {
dataDateTime = moment(stats[index]['time']).format(dataDateTimeFormat);
// occupation.push({'x': dataDateTime, 'y': stats[index]['occupation']});
// liveness.push({'x': dataDateTime, 'y': stats[index]['liveness']});
// efficiency.push({'x': dataDateTime, 'y': stats[index]['efficiency']});
occupation.push(stats[index]['occupation']);
liveness.push(stats[index]['liveness']);
efficiency.push(stats[index]['efficiency']);
labels.push({dataDateTime});
}
let fill = false;
let color = Chart.helpers.color;
let data = {
labels: labels,
datasets: [{
label: 'Screens',
pointRadius: 0,
tension: 0,
backgroundColor: color(window.chartColors.green).alpha(0.5).rgbString(),
borderColor: window.chartColors.green,
fill: fill,
data: liveness
},{
label: 'Occupation',
pointRadius: 0,
tension: 0,
backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
borderColor: window.chartColors.blue,
fill: fill,
data: occupation
},{
label: 'Efficiency',
pointRadius: 0,
tension: 0,
backgroundColor: color(window.chartColors.orange).alpha(0.5).rgbString(),
borderColor: window.chartColors.orange,
fill: fill,
data: efficiency
}]
};
let chartOptions = {
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
stepSize: 10,
max: 100
},
scaleLabel: {
display: true,
labelString: 'Percentage'
}
}],
xAxes: [{
//editing this will mess it up pretty bad
}]
},
tooltips: {
callbacks: {
label: function(value, index) {
return index.datasets[value.datasetIndex].label + ": " + value.yLabel;
},
}
}
};
The thing is, I tried several times to edit the x-axis option but it keeps messing the output
Your variable dataDateTime, for some reason, you are pushing it as an object in the label value, right here:
labels.push({dataDateTime});
That's why you are getting an X-axis label with [Object object]... You have two possible solutions:
1.Change the push:
labels.push(dataDateTime);
2.Add a callback to the xAxes[0].ticks property:
xAxes: [{
ticks: {
callback: function(value, index, values) {
return value.dataDateTime
}
}
}]
Both will work well (I tested), you also can check this fiddle that I made, to check it working (using the first solution)

Categories

Resources