Loop to create lines chart in canvasjs - javascript

I have an array Object:
total =
[
{
date: 5/12/2017,
count: 5,
type: A
},
{
date: 5/15/2017,
count: 15,
type: A
},
{
date: 5/12/2017,
count: 4,
type: B
},
{
date: 5/15/2017,
count: 5,
type: C
}..
]
I wondering how to loop them in a line chart using CanvasJS, each line presents each type, the x-axis presents date, the y-axis presents count
Here is what I have so far:
var chart = new CanvasJS.Chart("chartContainer",
{
title: {
text: "My Counts"
},
axisX: {
title: "Date",
},
axisY: {
title: "Count"
},
data: []
});

You can run a for loop over your array and store dataPoints in different variable to later use it in your chart.
var dps1 = [];
var dps2 = [];
var dps3 = [];
for(var i = 0; i < total.length; i++) {
if(total[i].type === "A") {
dps1.push({x: new Date(total[i].date), y: total[i].count});
} else if(total[i].type === "B") {
dps2.push({x: new Date(total[i].date), y: total[i].count});
} else if(total[i].type === "C") {
dps3.push({x: new Date(total[i].date), y: total[i].count});
}
}
Once you store you dataPoints, you'll need to use it in your chart.
data: [{
type: "line",
dataPoints: dps1
}, {
type: "line",
dataPoints: dps2
}, {
type: "line",
dataPoints: dps3
}]

Related

Chart JS custom message on tooltip, not x and y axis

I am displaying a bar chart that has 3 different pieces of information, (project name, number of days remaining, and the end date.) I am displaying the project name on one axis, and the number of days remaining determines the height of the bar. Currently, when I hover over a bar the tooltip displays the information already on the x and y axis. I want it to instead have the end date.
ie: project "b" will end in 2 days (August 4th), when I hover over the bar I want the tooltip to say "End date of 2022-08-04" instead of "b Work Days Remaining: 2"
My json of the data looks like this:
[{"po_num": "a", "days_rem": 10, "date_end": "2022-08-16"},
{"po_num": "b", "days_rem": 2, "date_end": "2022-08-04"},
{"po_num": "c", "days_rem": 6, "date_end": "2022-08-10"}]
Here is the link of the current graph.
https://i.stack.imgur.com/HefRz.png
Here is an MS paint rendering of what I am trying to do:
https://i.stack.imgur.com/GAT2I.png
The implementation code:
link = "{{{BASE_BACK_URL}}}";
$.getJSON(link, function (data) {
let po_names = [];
let days_rem = [];
for (let i = 0; i < data.length; i++) {
po_names.push(data[i]["po_num"]);
days_rem.push(data[i]["days_rem"]);
}
const ctx = document.getElementById('po-timeline-chart');
const myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: po_names,
datasets: [{
label: 'Work Days Remaining',
data: days_rem,
backgroundColor: 'rgb(0, 89, 178)'
}],
},
options: {
legend: {
align: "end"
},
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
});
Solution listed below:
$.getJSON(link, function (data) {
let po_names = [];
let days_rem = [];
for (let i = 0; i < data.length; i++) {
po_names.push(data[i]["po_num"]);
days_rem.push(data[i]["days_rem"]);
}
const ctx = document.getElementById("po-timeline-chart");
const myChart = new Chart(ctx, {
type: "horizontalBar",
data: {
labels: po_names,
datasets: [
{
label: "Work Days Remaining",
data: days_rem,
backgroundColor: "rgb(0, 89, 178)",
},
],
},
options: {
tooltips: {
enabled: true,
callbacks: {
// To change title in tooltip
title: (data) => {
return "This PO will run out on";
},
// To change label in tooltip
label: (data) => {
return date_end[data['index']];
},
},
},
legend: {
align: "end",
},
scales: {
xAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
},
});
});

how can i get percentage of each pie slice in Chart.js

I wanted to get percentage of each slice of pie . I am using chart.js for visualizing feedback results. Below is the code i am using
<script>
var xValues = ["very satisfied", "satisfied", "neutral", "dissatisifed", "very dissatified"];
var yValues = {{ faculty_feedback_data }};
var barColors = [
"#b91d47",
"#00aba9",
"#2b5797",
"#e8c3b9",
"#1e7145"
];
faculty_questionnaire = [questions are inserted here ]
faculty_chart_ids = ["faculty-chart1", "faculty-chart2", "faculty-chart3", "faculty-chart4", "faculty-chart5", "faculty-chart6", "faculty-chart7", "faculty-chart8", "faculty-chart9", "faculty-chart10", "faculty-chart11", "faculty-chart12", "faculty-chart13"]
for (let i = 0; i < faculty_chart_ids.length; i++) {
new Chart(faculty_chart_ids[i], {
type: "pie",
data: {
labels: xValues,
datasets: [{
backgroundColor: barColors,
data: yValues[i]
}]
},
options: {
title: {
display: true,
text: faculty_questionnaire[i]
},
},
});
}
</script>

Create Pie chart for each Json object

I have one Json with multiple array and foreach array I want to create Pie chart, but I don't know how to do it.
This is the array thet I have. And this is what I tried :
function Pie() {
$.getJSON("/Admin/Attivita/OreOggi", function (data) {
console.log(data);
var oreTecico = [];
var oreTecico = [];
var oreMalatia = [];
var oreStraordinario = [];
var oreInfortunio = [];
var oreFerie = [];
for (var i = 0; i < data.length; i++) {
nomeTecnico.push(data[i].nome);
oreTecico.push(data[i].odinario);
oreMalatia.push(data[i].malatia);
oreStraordinario.push(data[i].straordinario);
oreInfortunio.push(data[i].infortunio);
oreFerie.push(data[i].ferie);
};
// Build the chart
Highcharts.chart('zdravko', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Ore segnate oggi'
},
tooltip: {
pointFormat: '<b>{point.name}</b>: {point.y:.1f} h.'
},
accessibility: {
point: {
valueSuffix: '%'
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
name: nomeTecnico[0],
colorByPoint: true,
data: [{
name: '',
y:0,
sliced: true,
selected: true
}, {
name: 'Odinario',
y: oreTecico[0]
}, {
name: 'Malatia',
y: oreMalatia[0]
}, {
name: 'Straordinario',
y: oreStraordinario[0]
}, {
name: 'Infortunio',
y: oreInfortunio[0]
}, {
name: 'Ferie',
y: oreFerie[0]
}]
}]
});
});
}
It shows only the last "data". I want to make fo each array one pie. If i have 100 arrays I want 100 pies.
UPDATE:
I added this :
data.forEach(function (el) {
var chartData = [el.data1, el.data2];
var chartContainer = document.createElement('div');
document.getElementById('zdravko').append(chartContainer);
Highcharts.chart(chartContainer, {
series: [{
type: 'pie',
data: chartData
}]
});
});
The chartData is array of undefined objects.
Is it possible to make for or foreach inside Highcharts?
You need to use the Highcharts.chart method in a loop, for example:
var data = [{
data1: 12,
data2: 25
}, {
data1: 67,
data2: 11
}];
data.forEach(function(el) {
var chartData = [el.data1, el.data2];
var chartContainer = document.createElement('div');
document.getElementById('container').append(chartContainer);
Highcharts.chart(chartContainer, {
series: [{
type: 'pie',
data: chartData
}]
});
});
Live demo: http://jsfiddle.net/BlackLabel/x95pbw7j/
API Reference: https://api.highcharts.com/class-reference/Highcharts#.chart

Looping through data and passing it to a chart

I have an array of data that I'm using to plot a Line Chart. I'm using ApexCharts.
let testData = [
{
cell_id: 5833307,
datetime: ["2019-05-07 11:28:16.406795+03", "2019-05-07 11:28:38.764628+03", "2019-05-07 12:18:38.21369+03", "2019-05-07 12:33:47.889552+03", "2019-05-08 08:45:51.154047+03"],
rsrq: ["108", "108", "108", "108", "109"]
},
{
cell_id: 2656007,
datetime: ["2019-07-23 15:29:16.572813+03", "2019-07-23 15:29:16.71938+03", "2019-07-23 15:29:16.781606+03", "2019-07-23 15:29:50.375931+03", "2019-07-23 15:30:01.902013+03"],
rsrq: ["120", "119", "116", "134", "114"]
}
];
let datasetValue = [];
for( let x=0; x<testData.length; x++ )
{
datasetValue =
{
chart: {
height: 380,
width: "100%",
type: "line"
},
stroke: {
curve: 'smooth',
width: 1.5,
},
markers: {
size: 4,
},
legend: {
show: true,
position: 'top'
},
series: [
{
name: testData[x].cell_id,
data: testData[x].rsrq
}
],
xaxis: {
categories: testData[x].datetime,
title: {
text: "Date"
}
},
yaxis: {
title: {
text: "RSSI"
}
}
}
}
var chart = new ApexCharts(document.querySelector("#signal"), datasetValue);
chart.render();
<div id="signal"></div>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
So I take my JSON array, loop it in a for loop to obtain my datasets. I define an array variable datasetValue which i assign the looped data and pass it to my chart instance: new ApexCharts(document.querySelector("#rssi-signal"), datasetValue);
What is happening is only the last array object is being passed meaning there's something I'm missing/not passing to get all my data.
Restructure the testData by grouping series and categories
let series = [];
let categories = [];
for (let x = 0; x < testData.length; x++) {
series.push({
name: testData[x].cell_id,
data: testData[x].rsrq
});
categories.concat(testData[x].datetime);
}
let testData = [{
cell_id: 5833307,
datetime: ["2019-05-07 11:28:16.406795+03", "2019-05-07 11:28:38.764628+03", "2019-05-07 12:18:38.21369+03", "2019-05-07 12:33:47.889552+03", "2019-05-08 08:45:51.154047+03"],
rsrq: ["108", "108", "108", "108", "109"]
},
{
cell_id: 2656007,
datetime: ["2019-07-23 15:29:16.572813+03", "2019-07-23 15:29:16.71938+03", "2019-07-23 15:29:16.781606+03", "2019-07-23 15:29:50.375931+03", "2019-07-23 15:30:01.902013+03"],
rsrq: ["120", "119", "116", "134", "114"]
}
];
let series = [];
let categories = [];
for (let x = 0; x < testData.length; x++) {
series.push({
name: testData[x].cell_id,
data: testData[x].rsrq
});
categories = categories.concat(testData[x].datetime);
}
var chart = new ApexCharts(document.querySelector("#signal"), {
chart: {
height: 380,
width: "100%",
type: "line"
},
stroke: {
curve: 'smooth',
width: 1.5,
},
markers: {
size: 4,
},
legend: {
show: true,
position: 'top'
},
series: series,
xaxis: {
categories: categories,
title: {
text: "Date"
}
},
yaxis: {
title: {
text: "RSSI"
}
}
});
chart.render();
<div id="signal"></div>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
Since you are declaring an array outside the forloop
let datasetValue = {
chart: {
height: 380,
width: "100%",
type: "line"
},
stroke: {
curve: 'smooth',
width: 1.5,
},
markers: {
size: 4,
},
legend: {
show: true,
position: 'top'
},
series: [],
xaxis: {
categories: [],
title: {
text: "Date"
}
},
yaxis: {
title: {
text: "RSSI"
}
}
};
Inside for loop you should do
datasetValue.series.push(
{
name: testData[x].cell_id,
data: testData[x].rsrq
});
datasetValue.xaxis.categories.push(testData[x].datetime);
You should push the value inside the array instead of reassigning it in each iteration
The first mistake you are trying to do is defining the "datasetValue" as an array variable.
datasetValue = yourdata; //wrong in case of pushing data into array
You are trying to assign an object to array variable that contains only last results due to looping and assignment.
Instead, use push method of array to push the data into an array.
datasetValue.push(yourdata); //correct way to push data to array
So, there is no use to define "datasetValue" as array.
To achieve your objective you can apply loop with following
var datasetValue;
var series = [];
var categories = [];
for(let x=0; x<testData.length;x++) {
series.push({
name: testData[x].cell_id,
data: testData[x].rsrq
});
categories.concat(testData[x].datetime);
}
datasetValue = {
chart: {
height: 380,
width: "100%",
type: "line"
},
stroke: {
curve: 'smooth',
width: 1.5,
},
markers: {
size: 4,
},
legend: {
show: true,
position: 'top'
},
series,
xaxis: {
categories,
title: {
text: "Date"
}
},
yaxis: {
title: {
text: "RSSI"
}
}
};
var chart = new ApexCharts(document.querySelector("#signal"), datasetValue);
chart.render();
I move your for loop after datasetValue definition to add only series to it, and also change xaxis
for( let x=0; x<testData.length; x++ )
{
datasetValue.series.push({
name: testData[x].cell_id,
data: testData[x].rsrq
})
}
let testData = [
{
cell_id: 5833307,
datetime: ["2019-05-07 11:28:16.406795+03", "2019-05-07 11:28:38.764628+03", "2019-05-07 12:18:38.21369+03", "2019-05-07 12:33:47.889552+03", "2019-05-08 08:45:51.154047+03"],
rsrq: ["108", "108", "108", "108", "109"]
},
{
cell_id: 2656007,
datetime: ["2019-07-23 15:29:16.572813+03", "2019-07-23 15:29:16.71938+03", "2019-07-23 15:29:16.781606+03", "2019-07-23 15:29:50.375931+03", "2019-07-23 15:30:01.902013+03"],
rsrq: ["120", "119", "116", "134", "114"]
}
];
let datasetValue =
{
chart: {
height: 380,
width: "100%",
type: "line"
},
stroke: {
curve: 'smooth',
width: 1.5,
},
markers: {
size: 4,
},
legend: {
show: true,
position: 'top'
},
series: [
],
xaxis: {
categories: testData[0].datetime,
title: {
text: "Date"
}
},
yaxis: {
title: {
text: "RSSI"
}
}
}
for( let x=0; x<testData.length; x++ )
{
datasetValue.series.push({
name: testData[x].cell_id,
data: testData[x].rsrq
})
}
var chart = new ApexCharts(document.querySelector("#signal"), datasetValue);
chart.render();
<div id="signal"></div>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

Highcharts: How to display each column as a separate series?

I'm trying to display the data from my json.
My json file looks like this:
0: {OGS: "26", STRM: "1811", ACAD_CAREER: null, YEAR: "2018"}1: {OGS: "4144", STRM: "1801", ACAD_CAREER: null, YEAR: "2018"}2: {OGS: "3935", STRM: "1802", ACAD_CAREER: null, YEAR: "2018"}3: {OGS: "16", STRM: "1812", ACAD_CAREER: null, YEAR: "2018"}length: 4__proto__: Array(0)
And here's my code:
<script>
$(function () {
var categData = [];
var statusACountData = [];
var statusBCountData = [];
var dateVal=[];
var statusVal=[];
var countVal = [];
var jsonvar = [];
$.getJSON('http://localhost:37590/get_OGSDataPerTermYear/ORT/2018', function (jsonData) {
for(i=0;i<jsonData.length;i++){
dateVal[i]=jsonData[i].STRM;
// statusVal[i]=jsonData[i].status;
countVal[i]=jsonData[i].OGS;
}
// jsonData
console.log(jsonData);
console.log(countVal);
console.log(categData);
// $(function () {
Highcharts.chart('container', {
chart: {
type: 'column'
},
xAxis: {
categories: dateVal,
crosshair: true
},
series: [{
name: dateVal,
data: countVal
}]
});
// });
});
});
</script>
The column is not showing and the 4 data which is: 1801 1802 1803 and 1804 only appears in 1 series. I want to make them each series with different data which is OGS number.
To make it as you expect (each column is a separate series) you can follow this approach:
Prepare series and xAxis.categories arrays. Each series.data array should have an appropriate amount of null points before the one with real value. Something like that:
categories:
["1811", "1801", "1802", "1812"]
series:
[{
name: "cat - 0",
data: [2456]
}, {
name: "cat - 1",
data: [null, 4144]
}, {
name: "cat - 2",
data: [null, null, 3935]
}, {
name: "cat - 3",
data: [null, null, null, 2316]
}]
plotOptions.column.grouping should be disabled:
Highcharts.chart('container', {
chart: {
type: 'column'
},
xAxis: {
crosshair: true,
categories: categories
},
plotOptions: {
column: {
grouping: false
}
},
series: series
});
Demo:
https://jsfiddle.net/BlackLabel/ynqjftLk/
API reference:
https://api.highcharts.com/highcharts/plotOptions.column.grouping
enter image description hereYour data is not in right format. If you need to plot STRM is x axis , you will need to put them in a separate array and assign it to xAxis.
The yAxis also accepts an array of objects and the object need to have two keys like name & data where data is an array .
Also OGS values are in string , so adding a + before jsonData[i].OGS will convert it to number.
let jsonData = [{
OGS: "2456",
STRM: "1811",
ACAD_CAREER: null,
YEAR: "2018"
}, {
OGS: "4144",
STRM: "1801",
ACAD_CAREER: null,
YEAR: "2018"
}, {
OGS: "3935",
STRM: "1802",
ACAD_CAREER: null,
YEAR: "2018"
}, {
OGS: "2316",
STRM: "1812",
ACAD_CAREER: null,
YEAR: "2018"
}]
var categData = [];
var statusACountData = [];
var statusBCountData = [];
var dateVal = [];
var statusVal = [];
var countVal = [];
var jsonvar = [];
for (let i = 0; i < jsonData.length; i++) {
dateVal[i] = jsonData[i].STRM;
countVal.push({
name: 'someText',
data: [+jsonData[i].OGS]
})
}
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Some Text'
},
subtitle: {
text: 'someTExt'
},
xAxis: {
categories: dateVal,
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'OGS'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: countVal
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
can you guys check my code for drilldown? it only display 1 data series right after i clicked the column on the first chart,.
$.getJSON('http://localhost:37590/get_OGSDataPerTermYear/' + strCampus + "/" +
data[i].YEAR, function (jsonDataDrill) {
const datadrill = jsonDataDrill
console.log(jsonDataDrill);
for (d = 0; d < datadrill.length; d++) {
categories = datadrill[d].STRM
dataseries.push({
id: datadrill[d].YEAR,
name: +datadrill[d].STRM,
data: [{
y: +datadrill[d].OGS
}]
})
}
});

Categories

Resources