Make chartjs pie chart wiyh dynamic data - javascript

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 ?

Related

ChartJS chart is bugged after adding new data

Actually in my website i build a char with some data from MySQL Database.
Every time the chart button is pressed a modal will appear an AJAX call will be sent to the server and then the Chart will be drawn.
The issue is that after adding new data to database and by opening the modal with the ChartJS by moving the mouse the ChartJS tilt between chart with new data and the old one.
Here is the code
var chart;
$(function () {
renderChart();
});
function renderChart() {
var ctx = document.getElementById('barchart').getContext('2d');
var gradient = ctx.createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, '#007AFD');
gradient.addColorStop(1, '#00B1FF');
var options = {
legend: false,
maintainAspectRatio: false,
tooltips: {
displayColors: false
},
scales: {
xAxes: [{
gridLines: {
display: false,
},
barPercentage: 0.3,
}],
yAxes: [{
ticks: {
stacked: true,
stepSize: 1,
beginAtZero: true,
},
gridLines: {
borderDash: [5, 15],
drawBorder: false
}
}]
}
};
chart = new Chart(ctx, { type: 'bar', labels: [], data: [] });
}
function loadReports(data) {
$.ajax({
type: "POST",
url: "Default.aspx/getReports",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ data: data }),
dataType: "json",
success: function (r) {
data = r.d;
if (data != '[]') {
data = jQuery.parseJSON(data);
chart.data.labels = data.map(ora => ora.ORARIO);
chart.data.datasets[0].data[0] = data.map(cop => cop.COPERTI);
chart.update();
} else {
chart.data.labels = [];
chart.data.datasets[0].data = [];
chart.update();
}
},
error: function (error) {
alert(error.responseText);
}
});
}
buildChart() is called on load and chart is declared on top of JS file
Are you drawing a new chart by clicking on the button?
You should draw your chart just 1 time and then update the data:
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
function removeData(chart) {
chart.data.labels.pop();
chart.data.datasets.forEach((dataset) => {
dataset.data.pop();
});
chart.update();
}
Docs: https://www.chartjs.org/docs/latest/developers/updates.html
you can try it with this code:
$.ajax({
type: "POST",
url: "Default.aspx/getReports",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ data: data }),
dataType: "json",
success: function(r) {
data = r.d;
if (data != "[]") {
data = jQuery.parseJSON(data);
chart.data.labels = data.map(ora => ora.ORARIO);
chart.data.datasets[0].data = data.map(coperti => coperti.COPERTI);
chart.update();
} else {
chart.data.labels = [];
chart.data.datasets[0].data = [];
chart.update();
}
$("#modalChart").modal("show");
},
error: function(error) {
alert(error.responseText);
}
});

Display chartjs bar chart with dynamic data

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

Canvas JS not populating graph

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
}, {
},{
},..]

Data in highchart JSON format is correct

I have code like this
public static string summarydata(string RegNo)
{
try
{
TrackDataEntities1 sd = new TrackDataEntities1();
var mdata = new TrackDataEntities1().spsumdata(RegNo)
.Select(s => new { month = s.Month }).ToArray();
var sdata = new TrackDataEntities1().spsumdata(RegNo)
.Select(s => new { s.VName, s.total }).ToArray();
return Newtonsoft.Json.JsonConvert.SerializeObject(mdata) + "*" + Newtonsoft.Json.JsonConvert.SerializeObject(sdata);
}
catch (Exception)
{
throw new Exception();
}
}
now this return me data like this
"[{\"month\":\"July\"},{\"month\":\"June\"},{\"month\":\"June\"},
{\"month\":\"August\"},{\"month\":\"July\"},{\"month\":\"June\"},
{\"month\":\"May\"},{\"month\":\"June\"}]*[{\"VName\":\"DDSB\",\"total\":1},
{\"VName\":\"DPSB\",\"total\":1},{\"VName\":\"DSB\",\"total\":1},
{\"VName\":\"MV\",\"total\":5},{\"VName\":\"MV\",\"total\":11},
{\"VName\":\"MV\",\"total\":7},{\"VName\":\"MV\",\"total\":1},
{\"VName\":\"PSB\",\"total\":1}]"
jquery
UPDATED JQUERY
$(function () {
$('#tabledata').on('click', 'tr', function () {
var row = $(this);
var regno = row.find('td')[0].firstChild.data;
var obj = {};
obj.RegNo = regno;
Getsumdata(obj);
return false;
});
});
function Getsumdata(obj) {
$.ajax({
type: "POST",
url: "WebForm1.aspx/summarydata",
data: JSON.stringify(obj),
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert(JSON.stringify(result.d));
var data1 = result.d.split('*')[0];
console.log(typeof (data1)); //Still a String...
var data11 = JSON.parse(data1);
console.log(data11); //
$('#sum').highcharts({
title: {
text: 'Combination chart'
},
xAxis: {
categories: data11,
title: {
text: null
}
},
labels: {
items: [{
html: 'Total fruit consumption',
style: {
left: '50px',
top: '18px',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'black'
}
}]
},
// series:data2
series: [{
type: 'column',
name: 'Jane',
data: [3, 2, 1, 3, 4]
}, {
type: 'column',
name: 'John',
data: [2, 3, 5, 7, 6]
}, {
type: 'column',
name: 'Joe',
data: [4, 3, 3, 9, 0]
},
]
});
}
});
}
</script>
but chart look like this
Now the question is JSON look correct i think so why data is not populated in chart .. i use BAR highchart
any solution please?
data2 is still a string, you have to parse it.
Take a look at the Docs on how to add chart data, you have to transform your current data.
var a = "[{\"month\":\"July\"},{\"month\":\"June\"},{\"month\":\"June\"}, {\"month\":\"August\"},{\"month\":\"July\"},{\"month\":\"June\"}, {\"month\":\"May\"},{\"month\":\"June\"}]*[{\"VName\":\"DDSB\",\"total\":1}, {\"VName\":\"DPSB\",\"total\":1},{\"VName\":\"DSB\",\"total\":1}, {\"VName\":\"MV\",\"total\":5},{\"VName\":\"MV\",\"total\":11}, {\"VName\":\"MV\",\"total\":7},{\"VName\":\"MV\",\"total\":1}, {\"VName\":\"PSB\",\"total\":1}]";
var d = a.split('*')[1];
console.log(typeof(d)); //Still a String...
var e = JSON.parse(d);
console.log(e); //Yay an object.
It seems that you are not passing correct data to categories and series's.
Please transform your data in such a way that,
data1 represent categories, should look like this
["May","June","July","August"]
while your data2 represent the series data which you want to plot for a given month, should look like below.
[1,10,12,5]

highcharts dynamically adding series with addSeries

I'm working on creating a dynamically created chart that will add a series if there isn't one and if there is one add a point. I'm getting an Uncaught TypeError: Cannot call method 'addSeries' of undefined. I've looked around and I can't find why it says that method is undefined.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
$(document).ready(function () {
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column',
events: {
load: requestData
}
},
title: {
text: 'Survey Chart'
},
xAxis: {
categories: [],
title: {
text: 'Question Number'
}
},
yAxis: {
title: {
text: 'Total Answered'
}
},
legend: {
layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true
},
series: []
});
with the document ready function taking up the entire script i have the following functions
function requestData() {
ajaxCall(chartCreate, createSeries, "services/Survey.svc/DoWork", "{}");
chart1.redraw();
};
function chartCreate(point) {
var temp;
temp = $.parseJSON(point.d);
$.each(temp, function (key, p) {
var seriesObj;
seriesObj = seriesExists(p.mcAnswer);
if (seriesObj.status == false) {
chart1.addSeries({name: '' + p.mcAnswer + '', data: [] });
chart1.series[seriesObj.count].addPoint(p.total, false);
} else {
chart1.series[seriesObj.count].addPoint(p.total, false);
}
});
};
//loops through all the series to see if the series exists.
//if true returns index and true if not just returns false
function seriesExists(name) {
var ct = 0;
//var len = chart1.series.length;
var len = 0;
if (len > 0) {
$.each(chart1.series, function (count, curSeries) {
if (curSeries.name == name) {
return { 'count': count, 'status': true };
}
ct = count;
});
}
return { 'count': ct, 'status': false };
}; function createSeries() {
alert("error");
};
//$.ajaxCall({successFun: function, errorFun: function, source: "", data: {}});
function ajaxCall(myFunSuccess, myFunError, url, data) {
//chart1 = chartTemp;
$.ajax({
type: "POST",
async: false,
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: myFunSuccess,
error: myFunError
});
//return chart1;
};
I'm able to use the ajax function call fine it's when I get to my chartCreate where I run into the problem.
The problem is that you're trying to add the serie before chart1 get your chart reference. That's why chart1 doens't have addSeries method.
You can see this issue here.
To fix it you can set manually the chart reference to chart1 before call requestData.
Like the following.
load: function() {
chart1 = this; // `this` is the reference to the chart
requestData();
}

Categories

Resources