Passing parameters to linechart angular typescript - javascript

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
}
}
}
});

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);
}

How to make range of labels in javascript graph

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);

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'
}
}
}
})

How to apply each color to each dataset

If dataset is not dynamic, or it is static we can apply individual color as own wish in chart.js library
var sub1= {
label: 'sub1',
data: sub1-data,
backgroundColor: '#3498db'
};
var girlsData = {
label: 'sub2',
data: sub2-data,
backgroundColor: '#16a085'
};
But dataset are generated from ajax in JSON format.
No matter how many dataset are in there, how to assign each color to each label ? So I have applied background color while defining variable. It displays in chart, but isn't being shown for label name
backgroundColor: ['red', 'blue', 'green', 'yellow', 'cyan'],
it has considered only one color to every subject. It has to distinguish each subject according to chart format, hasn't it ? how can I assign each subject color to label as shown in figure
var data = [{"0":"Nepali","1":"4","sub":"Nepali","gpa":"4"},{"0":"English","1":"3","sub":"English","gpa":"3"},{"0":"Math","1":"3","sub":"Math","gpa":"3"},{"0":"Science","1":"2","sub":"Science","gpa":"2"},{"0":"Social_Studies","1":"5","sub":"Social_Studies","gpa":"5"}]
window.onload=function(){
var sub = [];
var gpa = [];
for(var i in data) {
sub.push(data[i].sub);
gpa.push(data[i].gpa);
}
var densityCanvas = document.getElementById('student');
var subData = {
label: sub,
data: gpa,
backgroundColor: ['red', 'blue', 'green', 'yellow', 'cyan'],
};
var planetData = {
labels: sub,
datasets: [subData]
};
var chartOptions = {
title: {
display: true,
text: 'GPA Mark Figure'
},
scales: {
yAxes: [{
ticks: {
fixedStepSize: 1,
beginAtZero: true
}
}],
},
};
var barChart = new Chart(densityCanvas, {
type: 'bar',
data: planetData,
options: chartOptions
});
}
<html>
<head>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js'></script>
</head>
<body>
<canvas id='student'></canvas>
</body>
</html>
Instead of setting only one dataset, use one for each distinct data(Nepali,...), the down side of this implementation is that you will loss the x label.
var data = [{"0":"Nepali","1":"4","sub":"Nepali","gpa":"4"},{"0":"English","1":"3","sub":"English","gpa":"3"},{"0":"Math","1":"3","sub":"Math","gpa":"3"},{"0":"Science","1":"2","sub":"Science","gpa":"2"},{"0":"Social_Studies","1":"5","sub":"Social_Studies","gpa":"5"}]
window.onload = function() {
var subData = [];
var colors = ['red', 'blue', 'green', 'yellow', 'cyan'];
for (var i in data) {
subData.push({
label: data[i].sub,
backgroundColor: colors[i],
data: [data[i].gpa]
});
}
var densityCanvas = document.getElementById('student');
var planetData = {
labels: [''],
datasets: subData
};
var chartOptions = {
title: {
display: true,
text: 'GPA Mark Figure'
},
scales: {
yAxes: [{
ticks: {
fixedStepSize: 1,
beginAtZero: true
}
}],
},
};
var barChart = new Chart(densityCanvas, {
type: 'bar',
data: planetData,
options: chartOptions
});
}
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js'></script>
<canvas id='student'></canvas>

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