Show No data message when chart has no data - javascript

I am trying to show no data message when chart has no data.
Is it correct?
var ctx = document.getElementById('mycanvas').getContext('2d');
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["aa", "bb", "cc", "dd"],
datasets: [{
label: "My First dataset",
backgroundColor: ['red', 'blue', 'green', 'yello'],
data: data.length ? data: [{ label: "No Data", value: 100 }],
}]
},
options: {
legend: {
position: 'right',
labels: {
boxWidth: 12
}
},
tooltips: { bodyFontSize: 12 }
}
});
I am not getting No data message when data length is 0.

Easiest is to use conditional rendering.
Assuming you're using AngularJS (you referenced tag), you can use ngIf directive. If data array is empty, then don't display chart.
<canvas id="myChart" ng-if="data != 0"></canvas>
<span ng-if="data == 0">No data</span>
Else, you can solve it in your script, by checking before or after draw the data length. I recommend you this snippet.
Other solution following your wish could be to adapt drawn data to received data.
if($scope.requestedLeaveTypeCount.length > 0){
data = {
labels: ["EL", "AL", "PL", "CL"],
datasets: [{
label: "My First dataset",
backgroundColor: ['#F0CB8C', '#A9D5D4', '#E8A3D7', '#CFA3FD'],
data: $scope.requestedLeaveTypeCount,
}]
}
} else {
data = {
labels: ["No data"],
datasets: [{
labels:'No data',
backgroundColor: ['#D3D3D3'],
data: [100]
}]
}
}
https://plnkr.co/edit/QXljAeeM4Ul3Y47EPcbq?p=preview

Related

Chart JS Displays Only Bigger Dataset But Has Both Datasets?

fairly new to JS and I have a strange issue with chart JS bar chart.
<script>
$(document).ready(function() {
var bar = document.getElementById("chart-bar-11").getContext('2d');
var data1 = {
labels: ["Yesterday"],
datasets: [{
label: "Win",
data: [{{ gam }}],
borderColor: '#4099ff',
backgroundColor: '#4099ff',
hoverborderColor:'#4099ff',
hoverBackgroundColor: '#4099ff',
}, {
label: "Lose",
data: [{{ results }}],
borderColor: '#0e9e4a',
backgroundColor: '#0e9e4a',
hoverborderColor:'#0e9e4a',
hoverBackgroundColor: '#0e9e4a',
}]
};
var myBarChart = new Chart(bar, {
type: 'bar',
data: data1,
options: {
barValueSpacing: 20
}
});
});
</script>
I have a simplke bar chart, but here is a screen shot of current behavior, super confused how this chart shows it has both datasets but will only display the larger dataset?
Ended up finding the options needed in another Chart JS post, this is what I was missing.
var myBarChart = new Chart(bar, {
type: 'bar',
data: data1,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
It appears he "beginAtZero" is what was missing. This now works as expected.

Chartjs using array in label field

I am making a simple bar chart using Chartjs 3.x
I make requests to a server to fetch json data and then store certain parts of it into arrays, here is the code for this:
serverData = JSON.parse(http.responseText);
console.log(serverData);
stundenProjekt = serverData.abzurechnen.nachProjekt.map((s) => {
return s.second.summe;
});
labelsP = serverData.abzurechnen.nachProjekt.map((p) => {
return p.first;
});
I then want to use these arrays in the data and label fields of the chart. I'm using stundenProjekt as data and it works fine, but when I use labelsP as label for the chart, it doesn't work. Here is the code of the chart:
const data = {
labels: labelsP,
datasets: [{
label: 'Projekte',
data: stundenProjekt,
backgroundColor: [
'#f4f40b',
],
borderColor: [
'#B1B101',
],
borderWidth: 3,
}]
};
if (barChartProjekt) {
data.datasets.forEach((ds, i) => {
barChartProjekt.data.datasets[i].data = ds.data;
barChartProjekt.labels = newLabelsArray;
})
barChartProjekt.update();
} else {
barChartProjekt = new Chart(chart, {
type: 'bar',
data: data,
options: {
responsive: true,
plugins: {
legend: {
labels: {
color: "white",
font: {
size: 18
}
}
}
},
scales: {
y: {
ticks: {
color: "white",
font: {
size: 18,
},
stepSize: 1,
beginAtZero: true
}
},
x: {
ticks: {
color: "white",
font: {
size: 14
},
stepSize: 1,
beginAtZero: true
}
}
}
}
});
}
The only workaround I have found is to copy the contents of labelsP and paste them in the label field. These are the contents of labelsP and how I did the workaround:
["nexnet-SB-Cloud", "AUTEC - PSK-System²", "Fritzsche", "nexnet-eBalance", "IfT - Neuentwicklung", "wattform", "Migration", "Fahrwerkregelkreis", "bmp greengas", "nexnet-SQL-Abfragen über API", "lambda9", "Nord Stadtwerke", "edifact", "SOLVIT", "BürgerGrünStrom", "SOLVCPM", "lambda captis", "SOLVEDI", "green city power", "max.power"]
const data = {
labels: ["nexnet-SB-Cloud", "AUTEC - PSK-System²", "Fritzsche", "nexnet-eBalance", "IfT - Neuentwicklung", "wattform", "Migration", "bmp greengas", "Fahrwerkregelkreis", "nexnet-SQL-Abfragen über API", "lambda9", "Nord Stadtwerke", "edifact", "SOLVIT", "BürgerGrünStrom", "SOLVCPM", "lambda captis", "SOLVEDI", "green city power", "max.power"],
datasets: [{
label: 'Projekte',
data: stundenProjekt,
backgroundColor: [
'#f4f40b',
],
borderColor: [
'#B1B101',
],
borderWidth: 3,
}]
};
In this way, the chart works and everything shows up as it should, however, I want to use it as shown in the first snippet of code, as labelsP gets updated every some seconds with new data extracted from the server. So, why is it that if I put labelsP alone in the label field it doesn't work, but if I copy and paste the contents of labelsP in the label field, it does work?
The problem is that you add the labels to the wrong position in the chart configuration.
Instead of...
barChartProjekt.labels = newLabelsArray;
try this...
barChartProjekt.data.labels = newLabelsArray;

ChartJS: Horizontal Bar with multiple datasets not showing Bars

I have Horizontal Bar comparing Rooms & Guests target vs achieved.
Rooms has 3 data values (Available, Budget, Actual) and Guests has only 2 (Budget, Actual).
Below is the code generates the chart:
data = [{
label: 'Available',
backgroundColor: '#3366ff',
data: [5580]
}, {
label: 'Budget',
backgroundColor: '#009999',
data: [5000, 6500]
}, {
label: 'Actual',
backgroundColor: '#92d400',
data: [5200, 7245]
}];
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ["Rooms", "Guests"],
datasets: data
}
}
Issue with the above code is, Rooms Budget bar is not showing up.
It shows only when I add [5580,0] to the Guests Available data value; however there is no such Data for Guests like Rooms.
Here is the JSFiddle (https://jsfiddle.net/kingBethal/vtf17k84/8/).
5000 is the lowest value in your dataset and Chart.js is creating its scale starting at 5000:
Set the beginAtZero property to true and you'll see the expected bar:
let data = [{
label: 'Available',
backgroundColor: '#3366ff',
data: [5580]
}, {
label: 'Budget',
backgroundColor: '#009999',
data: [5000, 6500]
}, {
label: 'Actual',
backgroundColor: '#92d400',
data: [5200, 7245]
}];
let myChart = new Chart(document.getElementById('chart'), {
type: 'horizontalBar',
data: {
labels: ["Rooms", "Guests"],
datasets: data
},
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chart"></canvas>

Pushing data from json to Chart.js labels and data

I am using the Chart.js lib to make charts.
I have a json array that I am getting from a database.
Here is the console log of it: Data
I need to get the address, speed, and speed limit for every element in the list and use it in a chart.
My current code is as follows:
function ShowChart() {
var popCanvas = document.getElementById("speedLimitsChart");
console.dir(speeddata);
var labels = speeddata.map(function (e) {
return e.Adress;
});
var speed = speeddata.map(function (e) {
return e.Speed;
});
var speedlimits = speeddata.map(function (e) {
return e.SpeedLimits;
});
console.dir(labels);
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
labels: labels
});
}
But in the result I only have the first element in my chart, and there are no labels.
Here is the output screen: Chart
I checked speed, speedlimits and labels and all of them have 2 elements. Can you please advise where my problem might be?
I found where is my problem
I need to write labels inside of data
Like this
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
labels: labels ,
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
});

How to bind json array data to chart.js with same canvas id?

My HTML Canvas is like below :
<div>
<canvas id="chartdiv" width="200" height="200"></canvas>
</div>
Following is the json data,
[{
"SID": "1",
"NAME": "niten",
"FTEPERCENT": "71.29",
"FTCPERCENT": "28.71"
}, {
"SID": "2",
"NAME": "jiten",
"FTEPERCENT": "82.08",
"FTCPERCENT": "17.92"
}]
And below is the enter code :
window.onload = function() {
$.ajax({
type: "POST",
url: "ViewDirectManagersOverviewDetails.aspx/GetEmployeeOverviewDetailsForDirectManagers",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(Result) {
debugger;
Result = JSON.parse(Result.d);
var newctx1;
for (var i = 0; i < Result.length; i++) {
var data1 = parseFloat(Result[i].FTEPERCENT);
var data2 = parseFloat(Result[i].FTCPERCENT);
var tempData = {
labels: ["FTE", "FTC"],
datasets: [{
data: [data1, data2],
backgroundColor: [
"#FF6384",
"#36A2EB"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB"
],
borderWidth: 5
}]
};
// For a pie chart1
var ctx = document.getElementById("chartdiv").getContext("2d");
var myLineChart = new Chart(ctx, {
type: "pie",
data: tempData,
options: options,
title: {
display: true,
text: 'Employee Overview',
fontStyle: 'bold',
fontSize: 20
}
});
}
$('chartdiv').append(newctx1);
}
});
};
The above code is plotting pie chart on same canvas id but I want to plot to separate pie charts since json has two array objects but canvas id should be same.
Looping through json will give two separate objects so I will have to draw in table two separate pie chart the way we show data in datatable similarly need to show pie charts in table rows.
Unfortunately, there is no way to render multiple charts within a single canvas. Chart.js binds to the entire canvas object and uses the full canvas to render a single chart.
If you want to see two separate pie charts then you need two separate canvas elements. However, you can of course add multiple datasets to a single graph if that suites your needs. For the pie chart it will embed a smaller pie chart within a larger one.
Here is an example config that shows how to setup multiple datasets in a single pie chart.
var ctx = document.getElementById("chart-area").getContext("2d");
var myPie = new Chart(ctx, {
type: 'pie',
data: {
labels: ["FTE", "FTC"],
datasets: [{
label: 'Dataset 1',
data: data1,
backgroundColor: [
"#FF6384",
"#36A2EB"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB"
],
borderWidth: 5,
}, {
label: 'Dataset 2',
data: data2,
backgroundColor: [
"#FF6384",
"#36A2EB"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB"
],
borderWidth: 5,
}],
},
options: {
title: {
display: true,
text: 'Employee Overview',
fontStyle: 'bold',
fontSize: 20
}
}
});
Here is a codepen example to demonstrate this.

Categories

Resources