chart.js : empty doughnut after getting data from database - javascript

Putting data from a database into an array in chart.js is not working and gives an empty doughnut:
i'm using angular / spring boot for back end
constructor(private statistiqueService:StatistiqueService) {
this.statistiqueService.getStateClient().subscribe(
resp=>{
for(var i=0;i<resp.length;i++){
this.dataStatus[i]=resp[i][1];
this.labelStatus[i]=resp[i][0];
}
}
);
}
statusClient(){
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [{
data: this.dataStatus,
backgroundColor: [
'rgba(255, 99, 132, 0.8)',
'rgba(54, 162, 235, 0.8)'
]
}],
labels:this.labelStatus
}
});
}
ngOnInit() {
console.log("Data");
console.log(this.dataStatus);
console.log("Label");
console.log(this.labelStatus);
this.statusClient();
}
My data after log is here

Related

json file to charts

I'm doing a project which is to extract data from python and show it in jsp dashboard.
I'm trying to load a json file to chartjs but it's not giving result
<script>
$.getJSON("resources/json_test.json", function(data) {
var labels = data.department.map(function(e) {
return e[1];
});
var data = data.volunteer.map(function(e) {
return e[1];
});
var context = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(context, {
type : 'bar',
data : {
labels : labels,
datasets : [ {
label : 'volunteer',
lineTension : 0.1,
data : data,
backgroundColor : "rgba(255, 99, 132, 0.2)"
}]
}
});
});
{"department":{"0":"IT","1":"Math","2":"English","3":"Software","4":"Game"},"volunteer":{"0":409,"1":1781,"2":476,"3":550,"4":562}}
To call .map() the datastructure needs to be an array, and since yours are objects it aint working, if you change your code to this it should work:
const labels = Object.values(data.department)
const parsedData = Object.values(data.volunteer)
const context = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(context, {
type: 'bar',
data: {
labels: labels,
datasets: [ {
label: 'volunteer',
lineTension: 0.1,
data: parsedData,
backgroundColor: "rgba(255, 99, 132, 0.2)"
}]
}
});

How use my data with Charts.js in my case?

I use Charts.js in my Angular project (not AngularJS) and i want to use data from my database to make a graphic with woman / man, but i didn't know how create a loop and count number of woman or number of men :
First, for the Chart, my html code :
<canvas id="myChart" width="700" height="400"></canvas>
typescript :
ngAfterViewInit() {
this.canvas = document.getElementById('myChart');
this.ctx = this.canvas.getContext('2d');
let myChart = new Chart(this.ctx, {
type: 'pie',
data: {
labels: ["Femme", "Homme"],
datasets: [{
label: '# of Votes',
data: [2,2],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: false,
display:true
}
});
}
and the code to get my data :
javascript :
app.get("/api/getUser",function(req,res){
model.find({},function(err,data){
if(err){
res.send(err);
}
else{
res.send(data);
}
});
})
typescript :
GetUser(){
return this.http.get('http://localhost:8080/api/getUser/')
.map((response: Response) => response.json())
}
and the second typescript :
ngOnInit() {
this.newService.GetUser().subscribe(data => this.Repdata = data)
}
for finish, this is the collection :
{
"_id" : ObjectId("5b9551a60e89ad15a8ff77fb"),
"name" : "XXX",
"prenom" : "KEVIN",
"datenaissance" : "17/11/2011",
"mail" : "KEVIN#laposte.fr",
"tel" : "XXXXXXXXXX",
"sexe" : "Homme",
"adresse" : "XXXXXXXX",
"note" : [
{
"matiere" : "Français",
"note" : "10/20",
"date" : "01/09/2018"
},
{
"matiere" : "Anglais",
"note" : "07/20",
"date" : "26/09/2018"
},
{
"matiere" : "EPS",
"note" : "15/20",
"date" : "29/09/2018"
}
]
}
I want to count the number of sexe:Homme and sexe:Femme to use this for create my graphic but i didn't know how
thank you very much
If I do this my charts can't find the countHomme and countFemme :
javascript :
app.get("/api/getUser",function(req,res){
model.find({},function(err,data){
if(err){
res.send(err);
}
else{
res.send(data);
var countHomme = model.where({ 'sexe': 'Homme' }).count();
res.send(countHomme);
var countFemme = model.where({ 'sexe': 'Femme' }).count();
res.send(countFemme);
}
});
})
typescript :
ngAfterViewInit() {
this.canvas = document.getElementById('myChart');
this.ctx = this.canvas.getContext('2d');
let myChart = new Chart(this.ctx, {
type: 'pie',
data: {
labels: ["Femme", "Homme"],
datasets: [{
label: '# of Votes',
data: [countFemme,countHomme],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: false,
display:true
}
});
}
IMO, its better to ask the data about male and female sex from the backend through an API.
You can try to count the fields using mongoose ORM via Model.count() method and it can send back a JSON object with total counts as per your need and you can feed it directly to chart.js

Update chart in Chart js

import Chart from "chart.js"
let AnalyticsChart = {
buildChart() {
let ctx = document.getElementById("analyticsChart");
let labels = ["sent", "delivered", "undelivered", "clicks"];
let total_sent = parseInt(document.getElementById("total-sent").dataset.totalSent);
let delivered = parseInt(document.getElementById("deilvered-count").dataset.deliveredCount);
let undelivered = parseInt(document.getElementById("undelivered-count").dataset.undeliveredCount);
let clicks = parseInt(document.getElementById("total-clicks").dataset.totalClicks);
let counts = [total_sent, delivered, undelivered, clicks]
let chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
data: counts,
backgroundColor: [
'rgba(54, 162, 235, 0.5)',
'rgba(255, 206, 86, 0.5)',
'rgba(255, 99, 132, 0.5)',
'rgba(75, 192, 192, 0.5)'
]
}]
},
options: {
}
});
},
update(){
}
}
export default AnalyticsChart
in this code I want to add update function to update chart.
I want to pass chart variable to update function how can I do this?
like this
update(chart) {
let total_sent = parseInt(document.getElementById("total-sent").dataset.totalSent);
let delivered = parseInt(document.getElementById("deilvered-count").dataset.deliveredCount);
let undelivered = parseInt(document.getElementById("undelivered-count").dataset.undeliveredCount);
let clicks = parseInt(document.getElementById("total-clicks").dataset.totalClicks);
let counts = [total_sent, delivered, undelivered, clicks]
chart.data.datasets.forEach((dataset) => {
dataset.data.push(counts) # How can I put individual counts value?
});
chart.update();
}
My questions
1. How can I pass chart variable in buildChart() to update function as parameter.
2. how can I put individual counts element in dataset.data.push(counts)?
I'm not familiar the way of your implement.
But it seems like java, so you need member variable, and access them using this from each function.
let AnalyticsChart = {
chart: null,
buildChart() {
/** omit **/
this.chart = new Chart(ctx, {
~
update() {
/** omit **/
this.chart.update();
I'm sorry I don't quite understand the question2.
Do you want to push the data, rather than update? If so, you can't do it just prepare the value. (I mean, you need labels, background...)
If you just want to update the chart, that is a piece of cake
this.chart.data.datasets.forEach((dataset) => {
dataset.data = counts;
});
Remember, you have one datasets.
If datasets is not dynamically, I think there's no need to loop.
this.chart.data.datasets[0].data = counts;

How to use JSON data in creating a chart with chartjs?

In my controller I have an Action method that will find all questions in a table called Questions, and the answers for each question.
This Action is of type ContentResult that will return a result serialized in Json format.
public ContentResult GetData()
{
var datalistQuestions = db.Questions.ToList();
List<PsychTestViewModel> questionlist = new List<PsychTestViewModel>();
List<PsychTestViewModel> questionanswerslist = new List<PsychTestViewModel>();
PsychTestViewModel ptvmodel = new PsychTestViewModel();
foreach (var question in datalistQuestions)
{
PsychTestViewModel ptvm = new PsychTestViewModel();
ptvm.QuestionID = question.QuestionID;
ptvm.Question = question.Question;
questionlist.Add(ptvm);
ViewBag.questionlist = questionlist;
var agree = //query
var somewhatAgree = //query
var disagree = //query
int Agree = agree.Count();
int SomewhatAgree = somewhatAgree.Count();
int Disagree = disagree.Count();
ptvmodel.countAgree = Agree;
ptvmodel.countSomewhatAgree = SomewhatAgree;
ptvmodel.countDisagree = Disagree;
questionanswerslist.Add(ptvmodel);
ViewBag.questionanswerslist = questionanswerslist;
}
return Content(JsonConvert.SerializeObject(ptvmodel), "application/json");
}
Now, my problem is the pie chart is not being created and I don't quite know how to push the values to my data structure?
What should I be doing instead?
Here is my script:
#section Scripts {
<script type="text/javascript">
var PieChartData = {
labels: [],
datasets: [
{
label: "Agree",
backgroundColor:"#f990a7",
borderWidth: 2,
data: []
},
{
label: "Somewhat Agree",
backgroundColor: "#aad2ed",
borderWidth: 2,
data: []
},
{
label: "Disgree",
backgroundColor: "#9966FF",
borderWidth: 2,
data: []
},
]
};
$.getJSON("/PsychTest/GetData/", function (data) {
for (var i = 0; i <= data.length - 1; i++) {
PieChartData.datasets[0].data.push(data[i].countAgree);
PieChartData.datasets[1].data.push(data[i].countSomewhatAgree);
PieChartData.datasets[2].data.push(data[i].countDisagree);
}
var ctx = document.getElementById("pie-chart").getContext("2d");
var myLineChart = new Chart(ctx,
{
type: 'pie',
data: PieChartData,
options:
{
responsive: true,
maintainaspectratio: true,
legend:
{
position : 'right'
}
}
});
});
</script>
You need two arrays for creating your chart. One of them indicates titles and another one shows the number of each titles. You have titles in the client side, so you only need the number of each options and it could be fetched from a simple server method like:
[HttpGet]
public JsonResult Chart()
{
var data = new int[] { 4, 2, 5 }; // fill it up whatever you want, but the number of items should be equal with your options
return JsonConvert.SerializeObject(data)
}
The client side code is here:
var aLabels = ["Agree","Somewhat Agree","Disagree"];
var aDatasets1 = [4,2,5]; //fetch these from the server
var dataT = {
labels: aLabels,
datasets: [{
label: "Test Data",
data: aDatasets1,
fill: false,
backgroundColor: ["rgba(54, 162, 235, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],
borderColor: ["rgb(54, 162, 235)", "rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],
borderWidth: 1
}]
};
var opt = {
responsive: true,
title: { display: true, text: 'TEST CHART' },
legend: { position: 'bottom' },
//scales: {
// xAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' } }],
// yAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' }, ticks: { stepSize: 50, beginAtZero: true } }]
//}
};
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx, {
type: 'pie',
data: dataT,
options: opt
});
<script src="https://github.com/chartjs/Chart.js/releases/download/v2.7.1/Chart.min.js"></script>
<div Style="font-family: Corbel; font-size: small ;text-align:center " class="row">
<div style="width:100%;height:100%">
<canvas id="myChart" style="padding: 0;margin: auto;display: block; "> </canvas>
</div>
</div>
If you are still looking to use json for chart.js charts.
Here is a solution which fetch a json file and render it on chart.js chart.
fetch('https://s3-us-west-2.amazonaws.com/s.cdpn.io/827672/CSVtoJSON.json')
.then(function(response) {
return response.json();
})
.then(function(ids) {
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: ids.map(function(id) {
return id.Label;
}),
datasets: [
{
label: "value2",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: ids.map(function(id) {
return id.Value2;
}),
},
{
label: "value",
//backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: ids.map(function(id) {
return id.Value;
}),
},
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Sample Json Data Chart'
}
}
});
});
see running code on jsfiddle here

Chart.js donut chart remains grey - no color

I have a donut chart being created by chart.js as follows:
<div id="chartContainer" style="height: 320px; width: 320px">
<canvas id="hoursFEContainer"></canvas>
</div>
I require chart.js as follows (downloaded from npm):-
require('chart.js');
Then in a relevant function I instantiated Chart.js as follows:-
var distinctFeeEarners = ['MEH', 'IHM'];
var totalHoursByFE = [0.8, 0.7];
var chartdata = {
labels: distinctFeeEarners,
datasets : [
{
label: 'Fee Earner',
data: totalHoursByFE
}
]
};
var ctx = $("#hoursFEContainer");
var donutChart = new Chart(ctx, {
type: 'doughnut',
backgroundColor:
['rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)'],
data: chartdata
});
The chart displays with the correct data, but the donut does not have any colours?
Whats wrong?
EDIT: Beyond stupid, backgroundColor needs to be in datasets not in new Chart. Nevermind.
The reason is that you define backgroundColor at the wrong place. It's a dataset property, hence needs to be defined inside the dataset.
var distinctFeeEarners = ['MEH', 'IHM'];
var totalHoursByFE = [0.8, 0.7];
var chartdata = {
labels: distinctFeeEarners,
datasets: [{
label: 'Fee Earner',
data: totalHoursByFE,
backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)']
}]
};
var donutChart = new Chart(document.getElementById('hoursFEContainer'), {
type: 'doughnut',
data: chartdata
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<div id="chartContainer" style="height: 320px; width: 320px">
<canvas id="hoursFEContainer"></canvas>
</div>
Had exactly the same problem with ng2-charts
What did it for me was not pre-initializing dataset.
Prevously i would declare empty array
public data: MultiDataSet = [];
then after backend request resolves i would assign new value
const dataset: Array<number> = new Array();
response.items.map(result => {
dataset.push(result);
});
this.data = [dataset];
This would print doughnut chart but without color. Everything was gray.
Simply not preinitializing MultiDataSet like this fixes things
public data: MultiDataSet; //=[];

Categories