I have jQuery code that uses the JSON responses from a RESTful web service to plot a graph. I am using Canvas JS for this task.
Whenever I run the program, i get an empty graph.
Any and all help is appreciated.
$(document).ready(function() {
$('form').on('submit', function(event) {
var date = $('#nameInput').val();
var datatmax = [];
var datatmin = [];
$.ajax({
data: {
v: $('#nameInput').val(),
},
type: 'GET',
url: '/forecast/' + date
}).done(function(data) {
if (data) {
$.each(data, function(d) {
datatmax.push({
y: d.TMAX,
label = d.DATE
})
datatmin.push({
y: d.TMIN,
label = d.DATE
})
})
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "WEATHER FORECAST"
},
data: [{
type: "line",
markerType: "circle",
name: "TMAX",
showInLegend: true,
dataPoints: datatmax
}, {
type: "line",
name: "TMIN",
lineDashType: "dash",
showInLegend: true,
markerType: "square",
dataPoints: datatmin
}]
});
chart.render();
}
});
event.preventDefault();
});
});
The JSON array is of the format
[{
'DATE': VAL,
'TMAX': VAL,
'TMIN': VAL
}, {
},{
},..]
Related
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
I need to display a bar chart that I must make with chartJs with dynamic data, I get these dynamic data from an xml link.
I work with two datafields: TaskName and TaskPercentCompleted
The final result must be something like this:
https://scontent.ftun3-1.fna.fbcdn.net/v/t1.15752-9/67290623_1101713790034749_6213821876259520512_n.png?_nc_cat=107&_nc_oc=AQkVef74ok1IcC0m0ujX4t7c4EhNAEs0C-lejsBTHCj9U2zrFRo2UA_gWnuOeA4ZJco&_nc_ht=scontent.ftun3-1.fna&oh=e8503be685f36c7440362b5a0d3c85f5&oe=5DA3B54E
And this is a part of the xml link:
https://scontent.ftun3-1.fna.fbcdn.net/v/t1.15752-9/66803472_2156647134463530_3324310068698021888_n.png?_nc_cat=100&_nc_oc=AQmuJ-gA1lT7F-whtw329vy_eciZoCWNn5hxCW2Zdp4X_RBfyZknVR1Bza-UF_nDn7s&_nc_ht=scontent.ftun3-1.fna&oh=d6ced2436a0c666be4dfd4fe5138a72f&oe=5DAADE21
I got a code but it doesn't work the way I want, it's regrouping data and I don't want that.
window.addEventListener('load',function() {
var dataURL = _spPageContextInfo.webAbsoluteUrl + "/_api/ProjectData/[en-US]/Tasks?$select=TaskName,TaskPercentCompleted&$filter=ProjectName%20eq%20%27Bay%20Plaza%27%20and%20TaskIsSummary%20eq%20true%20and%20TaskIsProjectSummary%20eq%20false";
$.ajax({
url: dataURL,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
var dataResults = data.d.results;
var itermeidiaryObject = {};
$.each(dataResults, function(key, value) {
var nomTask = value.TaskName;
var epn = value.TaskPercentCompleted;
if (epn != null) {
itermeidiaryObject[epn] = ++itermeidiaryObject[epn] || 1;
}
});
var finalObject = Object.keys(itermeidiaryObject).map(function(key) {
return {
label: itermeidiaryObject[key],
y: key
}
});
var pievalues = finalObject.map(function(value, index) {
return value.y;
});
var labels = finalObject.map(function(value, index) {
return value.label;
});
var colorscheme = colors.slice(0, labels.length);
var ctx = document.getElementById('myChart2').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
data: pievalues,
backgroundColor: colorscheme
}]
},
options: {
responsive: true,
scales: {
xAxes: [{
ticks: {
beginAtZero: true // Edit the value according to what you need
}
}],
yAxes: [{
stacked: true
}]
},
title: {
display: true,
position: "top",
text: "Nombre de projets par direction",
fontSize: 18,
fontColor: "#111"
},
legend: {
display: false
}
}
});
}
});
});
var colors = ["#0074D9", "#FF4136", "#2ECC40", "#FF851B", "#7FDBFF", "#B10DC9", "#FFDC00", "#001f3f", "#39CCCC", "#01FF70", "#85144b", "#F012BE", "#3D9970", "#111111", "#AAAAAA"];
I solved the problem
window.addEventListener('load',function() {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/ProjectData/[en-US]/Tasks?$select=TaskName,TaskPercentCompleted&$filter=ProjectName%20eq%20%27Bay%20Plaza%27%20and%20TaskIsSummary%20eq%20true%20and%20TaskIsProjectSummary%20eq%20false",
method: "GET",
headers: { "Accept": "application/json; odata=nometadata" },
success: function (data) {
if (data.value.length > 0) {
var pieValues = [];
var pieLabels = [];
for (var i = 0; i < data.value.length; i++) {
pieValues.push(parseInt(data.value[i].TaskPercentCompleted));
pieLabels.push(data.value[i].TaskName);
}
var pieData = {
datasets: [{
data: pieValues,
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850",
"#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850",
"#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850",
"#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850",
"#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850",
"#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
}],
labels: pieLabels
};
var ctx = document.getElementById("myChart2");
var myPieChart = new Chart(ctx, {
//type: 'pie',
type: 'bar',
data: pieData,
options: {
responsive: true,
legend: { display: false },
title: {
display: true,
text: 'Nom de tâche par pourcentage'
},
scales: {
xAxes: [{
ticks: {
maxRotation: 90,
minRotation: 90,
display: false
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
},
error: function (data) {
//
}
});
});
I can't display my ChartJS pie chart with dynamic data, I googled a lot and I couldn't find a solution, so I'm here for your help.
window.onload = function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
dataType: "json",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
// var dataResults = data.d.results;
var tempData = [{
EnterpriseProjectTypeName: 'first project'
},
{
EnterpriseProjectTypeName: 'first project'
},
{
EnterpriseProjectTypeName: 'first project'
},
{
EnterpriseProjectTypeName: 'second project'
},
{
EnterpriseProjectTypeName: 'third project'
},
{
EnterpriseProjectTypeName: 'test'
}
];
var itermeidiaryObject = {};
$.each(tempData, function(key, value) {
var epn = value.EnterpriseProjectTypeName;
var som = 0;
if (epn != null) {
itermeidiaryObject[epn] = ++itermeidiaryObject[epn] || 1;
}
var somme = som;
});
var finalObject = Object.keys(itermeidiaryObject).map(function(key) {
return {
label: key,
y: itermeidiaryObject[key]
}
});
var ctx = document.getElementById('myChart').getContext('2d');
var lables=tempData
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: finalObject,
datasets: [{
data: finalObject,
}]
},
options: {
responsive: false,
scales: {
xAxes: [{
ticks: {
maxRotation: 90,
minRotation: 80
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
});
}
And this is the html part
<canvas id="myChart"></canvas>
</div><script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
Can any one help me please?
Do you want a pie chart or a bar chart ? Edited things a little so that it makes a pie chart, although you can just go back to the bar chart with a few edits regarding mostly the way labels were handled since it looks like they need to be single values in an array. Probably a better way, but this should help. This is for the pie chart. You had a rogue div in the HTML also.
window.onload = function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
dataType: "json",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
// var dataResults = data.d.results;
var tempData = [{
EnterpriseProjectTypeName: 'first project'
},
{
EnterpriseProjectTypeName: 'first project'
},
{
EnterpriseProjectTypeName: 'first project'
},
{
EnterpriseProjectTypeName: 'second project'
},
{
EnterpriseProjectTypeName: 'third project'
},
{
EnterpriseProjectTypeName: 'test'
}
];
var itermeidiaryObject = {};
$.each(tempData, function(key, value) {
var epn = value.EnterpriseProjectTypeName;
var som = 0;
if (epn != null) {
itermeidiaryObject[epn] = ++itermeidiaryObject[epn] || 1;
}
var somme = som;
});
var finalObject = Object.keys(itermeidiaryObject).map(function(key) {
return {
label: key,
y: itermeidiaryObject[key]
}
});
var pievalues = finalObject.map(function(value, index) {
return value.y;
});
var labels = finalObject.map(function(value, index) {
return value.label;
});
var colorscheme = colors.slice(0, labels.length);
console.log(labels);
console.log(pievalues);
console.log(finalObject);
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: labels,
datasets: [{
data: pievalues,
backgroundColor: colorscheme
}]
},
options: {
responsive: false,
}
});
}
});
}
var colors = ["#0074D9", "#FF4136", "#2ECC40", "#FF851B", "#7FDBFF", "#B10DC9", "#FFDC00", "#001f3f", "#39CCCC", "#01FF70", "#85144b", "#F012BE", "#3D9970", "#111111", "#AAAAAA"];
<canvas id="myChart"></canvas>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
I am presuming that the data you provided in the handler success is pretty much what you get back as JSON ?
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
}]
My code successfully draws a chart with data and tick labels retrieved as JSON object from PHP. Now at one point i want to refresh the chart but with slightly different data and different tick labels without creating a new chart.
$.jqplot.config.enablePlugins = true;
var freqs1 = [];
var freqlabels1 = [];
var dataRendered1 = $.ajax({
async: false,
url: 'MY_URL',
dataType: 'json',
success: function(data) {
if (data.length) {
freqs1 = data[0];
freqlabels1 = data[1];
}
}
});
var plot1 = $.jqplot('chartdiv', [freqs1], {
animate: !$.jqplot.use_excanvas,
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
pointLabels: {
show: true
},
rendererOptions: {
barWidth: 12
}
},
title:'Test',
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: freqlabels1,
label: "Test 1",
tickOptions:{textColor : 'rgb(39, 125, 175)', fontSize: '9pt'}
},
yaxis: {
label: "Test 2",
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
tickOptions:{textColor : 'rgb(39, 125, 175)', fontSize: '9pt'}
}
},
highlighter: { show: true }
});
now when button is clicked lets say I have an ajax call that gets the new data and tick labels
$(document).on('click', '#refresh_new', function() {
$.ajax({
async: false,
url: 'MY_URL',
dataType: 'json',
success: function(data) {
var newData = data[0];
var newTicks = data[1];
//HOW DO I REFRESH CHART WITH NEW DATA AND TICKS FOR x-AXIS
}
});
});