How to get the angularjs scope variable data to the chartjs data - javascript
I am trying to pass the value from the scope variable of the angularjs controller to the chartjs data.
this is my master.controller.js - The chartjs is inside the master.controller.js file:
/**
* Master Controller
*/
// Global variables for chart.js
var totalTripsCompleted = '';
var TruckTripsFortheDay = [];
var totalTrucks = [];
var totalNumberofTripsCompleted = '';
var numberoftrucks = [];
angular.module('App')
.controller('MasterCtrl', ['$scope','$http','StorageService','PagingUtil','$state','$rootScope', function ($scope, $http, StorageService, PagingUtil, $state, $rootScope) {
$scope.client = false;
$scope.stateName = '';
$scope.loggedIn = false;
$scope.landingPage = "shipments"
var samplearrayvar = [];
$scope.init = function(){
}
// $scope.dueRenewal = 0;
// $scope.dueService = 0;
// $scope.dueSoonRenewal = 0;
// $scope.dueSoonService = 0;
$scope.user = {};
$scope.typeCount = [];
$scope.getDueRenewal = function(){
$http.get("/api/renewalReminders?status=due").success(function(response,status,headers){
$scope.dueRenewal = headers('X-Total-Count');
});
}
$scope.getDueService = function(){
$http.get("/api/serviceReminders?status=due").success(function(response,status,headers){
$scope.dueService = headers('X-Total-Count');
});
}
$scope.getDueSoonRenewal = function(){
$http.get("/api/renewalReminders?status=dueSoon").success(function(response,status,headers){
$scope.dueSoonRenewal = headers('X-Total-Count');
});
}
$scope.getDueSoonService = function(){
$http.get("/api/serviceReminders?status=dueSoon").success(function(response,status,headers){
$scope.dueSoonService = headers('X-Total-Count');
});
}
$scope.checkIfLoggedIn = function(){
$scope.user = StorageService.get("user");
$rootScope.user = false;
$http.get("/api/account").success(function(response){
$scope.loggedIn = true;
if($scope.user == null){
$scope.user = response;
$rootScope.user = response;
StorageService.save("user",$scope.user);
}
if($scope.user.login == response.login){
if($state.current.name=="login"){
$state.go($scope.landingPage);
}
}
}).error(function(){
$scope.loggedIn=false;
$scope.user = false;
if($state.current.name!="login" && $state.current.name!=$scope.landingPage){
console.log("last state");
$rootScope.attemptedState = $state.current.name;
$rootScope.attemptedStateParams = $state.params;
}
StorageService.clearAll();
$state.go("login");
});
}
$scope.redirectFromLastAttempt = function(){
if($rootScope.attemptedState){
var go = $rootScope.attemptedState;
$rootScope.attempatedState = false;
$state.go(go,$rootScope.attemptedStateParams);
return;
}
}
$scope.checkIfLoggedIn();
$scope.request = {};
$scope.login = function(){
$http.post("/api/authenticate",$scope.request)
.success(function(response){
$scope.checkIfLoggedIn();
});
}
$scope.changePassword = function(){
$http.post("/api/account/change_password",$scope.request)
.success(function(response){
$state.go($scope.landingPage);
}).error(function(response){
console.log(response);
alert("Cannot change password. invalid old password");
});
}
$scope.logout = function(){
StorageService.clearAll('user',$scope.user);
$http.delete("/api/authenticate?username="+$scope.request.username+"&password="+$scope.request.username)
.success(function(response){
$scope.checkIfLoggedIn();
}).error(function(response){
$scope.checkIfLoggedIn();
});
}
$rootScope.getDestinations = function(customerId,list){
$http.get("/api/destinations?customerId="+customerId).success(function(response){
list = response;
});
}
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
$scope.stateName = toState.name;
$scope.checkIfLoggedIn();
});
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
$scope.stateName = toState.name;
console.log($scope.stateName);
if($scope.stateName=='index'){
$scope.getDueRenewal();
$scope.getDueService();
$scope.getDueSoonRenewal();
$scope.getDueSoonService();
}
if(fromState.name){
$rootScope.fromState = fromState.name;
$rootScope.fromParams = fromParams;
}
});
$rootScope.showError = function(message,title){
$rootScope.errorMessage = message;
$rootScope.errorMessageTitle = null;
if(title){
$rootScope.errorMessageTitle = title;
}
$("#error-modal").modal('show');
};
$rootScope.$on('loading:progress', function (){
// show loading gif
$("#loading-modal").modal({keyboard:false,show:true,backdrop:'static'});
});
$rootScope.$on('loading:finish', function (){
// hide loading gif
// setTimeout(function(){
$("#loading-modal").modal("hide");
// },5000);
});
$rootScope.hasAccess = function(rolenames){
if($scope.user){
if($scope.user.roles){
if($scope.user.roles.indexOf('ROLE_ADMIN')>-1){
return true;
}
}else{
return false;
}
}else{
return false;
}
for(var i in rolenames){
if($scope.user.roles.indexOf(rolenames[i])>-1){
return true;
}
}
return false;
}
//Daily Truck Utilization-------------------------------------------------------------------------------
$scope.getTrucksDispatched = function() {
$scope.trucksample = [];
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth();
var year = currentDate.getFullYear();
$scope.truckdispatcheddate = "(" + month + "-" + day + "-" + year + ")";
$http.get("/api/shipmentstatusanddispatched").success(function(response){
totalTripsCompleted = response;
console.log(response);
});
}
$scope.getTotalNumberofTrucks = function() {
$http.get("/api/vehicleTrucks").success(function(response) {
$scope.totalNumberofTrucks = response[0];
console.log(response);
});
}
//Number of trips running-------------------------------------------------------------------------------
var samplearray = [];
$scope.getVehicleTypeCount = function(){
$http.get("/api/vehicleTrucks").success(function(response){
// for (var i = 0; i < response.length; i++) {
// var count = 0;
// var key = response[i].commodityType;
// $scope.count = {};
// for (var j = 0; j < response.length; j++) {
// if(response[j].commodityType == key){
// count++;
// }
// }
// $scope.count[key] = count;
// $scope.typeCount.push($scope.count);
// samplearray.push(response[i].commodityType);
// }
console.log(response);
});
}
$scope.numberOfTrips = function() {
$scope.getTotalCompletedTrips = '';
$http.get("/api/shipmentcountstatuscompleted").success(function(response) {
$scope.getTotalCompletedTrips = response;
totalNumberofTripsCompleted = response;
console.log($scope.getTotalCompletedTrips);
});
}
//Number or % of Dry, Chilled, Reefer trips for the day--------------------------------------------
// $scope.getCommodityTypeVehicleQuantity = function() {
//
// //
// }
//% Truck break down ( repairs and maint) and average number of days down--------------------------
//POD status -dispatched, delivered, completed (running) / unbilled--------------------------------
$scope.tripStatus = function() {
var dispatched = '';
var delivered = '';
var completed = '';
var totaltrips = '';
$http.get("/api/shipmentcountstatusdispatched").success(function(response) {
dispatched = response;
});
$http.get("/api/shipmentcountstatusdelivered").success(function(response) {
delivered = response;
});
$http.get("/api/shipmentcountstatuscompleted").success(function(response) {
completed = response;
});
$http.get("/api/shipmentTotaltrips").success(function(response) {
totaltrips = response;
});
$scope.completionrate = completed / totaltrips;
}
//Average Diesel consumption per client(?) against target------------------------------------------
$scope.tripStatus();
$scope.numberOfTrips();
$scope.getTotalNumberofTrucks();
$scope.getTrucksDispatched();
}]);
var trucksperdepotid = document.getElementById('trucksperdepot').getContext('2d');
var trucksperdepotChart = new Chart(trucksperdepotid, {
type: 'bar',
data: {
labels: ['Depot 1', 'Depot 2', 'Depot 3', 'Depot 4', 'Depot 5'],
datasets: [{
label: 'Number of Trucks per Depot',
data: [
90,
80,
70,
60,
50
],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
var tripscompletedid = document.getElementById('tripscompleted').getContext('2d');
var tripscompletedChart = new Chart(tripscompletedid, {
type: 'bar',
data: {
labels: ['Number of Trips Completed'],
datasets: [{
label: 'Number of trips completed',
data: [
totalNumberofTripsCompleted
],
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
// 'rgba(255, 99, 132, 0.2)',
// 'rgba(54, 162, 235, 0.2)',
// 'rgba(255, 206, 86, 0.2)',
// 'rgba(75, 192, 192, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(255, 159, 64, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(153, 102, 255, 0.2)',
// 'rgba(153, 102, 255, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)'
// 'rgba(255,99,132,1)',
// 'rgba(54, 162, 235, 1)',
// 'rgba(255, 206, 86, 1)',
// 'rgba(75, 192, 192, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(255, 159, 64, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(153, 102, 255, 1)',
// 'rgba(153, 102, 255, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
var commoditytypeid = document.getElementById('commoditytype').getContext('2d');
//commoditytypeid.height=100;
var commoditytypeChart = new Chart(commoditytypeid, {
type: 'pie',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var commoditytypetodayid = document.getElementById('commoditytypetoday').getContext('2d');
//commoditytypeid.height=100;
var commoditytypeChart = new Chart(commoditytypetodayid, {
type: 'pie',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var commoditytypeyesterdayid = document.getElementById('commoditytypeyesterday').getContext('2d');
//commoditytypeid.height=100;
var commoditytypeChart = new Chart(commoditytypeyesterdayid, {
type: 'pie',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var commoditytypethisweekid = document.getElementById('commoditytypethisweek').getContext('2d');
//commoditytypeid.height=100;
var commoditytypeChart = new Chart(commoditytypethisweekid, {
type: 'pie',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var commoditytypethismonthid = document.getElementById('commoditytypethismonth').getContext('2d');
//commoditytypeid.height=100;
var commoditytypeChart = new Chart(commoditytypethismonthid, {
type: 'pie',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var truckdownid = document.getElementById("truckdown").getContext("2d");
var truckdownChart = new Chart(truckdownid, {
type: 'bar',
data: {
labels: ['Truck Down'],
datasets: [{
label: 'Vehicles with On-Service Status',
backgroundColor: "rgba(255, 99, 132, 0.2)",
borderColor: 'rgba(255,99,132,1)',
data: [80]
}, {
label: 'Number of fleet',
backgroundColor: "rgba(54, 162, 235, 0.2)",
borderColor: 'rgba(54, 162, 235, 1)',
data: [90]
}]
},
options: {
legend: {
display: true,
labels: {
fontColor: "#000080",
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
var truckdownaverageid = document.getElementById("truckdownaverage").getContext("2d");
var truckdownaverageChart = new Chart(truckdownaverageid, {
type: 'bar',
data: {
labels: ['Truck Down Average'],
datasets: [{
label: 'Vehicles with On-Service Status',
backgroundColor: "rgba(255, 99, 132, 0.2)",
borderColor: 'rgba(255,99,132,1)',
data: [80]
}, {
label: 'Number of fleet',
backgroundColor: "rgba(54, 162, 235, 0.2)",
borderColor: 'rgba(54, 162, 235, 1)',
data: [90]
}]
},
options: {
legend: {
display: true,
labels: {
fontColor: "#000080",
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
var tripstatusforthemonthid = document.getElementById('tripstatusforthemonth').getContext('2d');
//commoditytypeid.height=100;
var tripstatusforthemonthChart = new Chart(tripstatusforthemonthid, {
type: 'pie',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var tripscreatedid = document.getElementById('tripscreated').getContext('2d');
var tripscreatedChart = new Chart(tripscreatedid, {
type: 'doughnut',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
var averagedieselconsumptionid = document.getElementById('averagedieselconsumption').getContext('2d');
var averagedieselconsumptionChart = new Chart(averagedieselconsumptionid, {
type: 'doughnut',
data: {
datasets: [{
data: [
20,
30,
40,
50
],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}],
labels: [
'Dry',
'Chilled',
'Frozen',
'Wet'
]
},
options: {
}
});
I am trying to get the value of the $scope.totalNumberofTrucks to the data of the chartjs. But when i try to pass the value of that scope to a global variable, the global variable I declared in the chartjs data is still empty / null.
Related
Chart.js not showing value on top of bars
I started to learn chart.js a while ago and got stuck where the bars are not showing the value on top bars, and how do I add percentage sign after the value? I use chart.js 3.3.2 cdn btw. Please I need help let myChart = document.getElementById('myChart').getContext('2d'); const label = ['A','B','C','D','E']; const datas = [85, 90, 53, 100, 76]; const backgroundColors = [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)' ]; const borderColors = [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)' ] let iChart = new Chart(myChart, { type: 'bar', data: { labels: label, datasets: [{ label: 'EQA-Übereinstimmung', data: datas, backgroundColor: backgroundColors, borderColor: borderColors, borderWidth: 1 }] }, options: { responsive:true, maintainAspectRatio: false, animation: { duration: 1, onComplete: function () { var chartInstance = this.chart, myChart = chartInstance.myChart; myChart.textAlign = 'center'; myChart.fillStyle = "rgba(0, 0, 0, 1)"; myChart.textBaseline = 'bottom'; // Loop through each data in the datasets this.data.datasets.forEach(function (dataset, i) { var meta = chartInstance.controller.getDatasetMeta(i); meta.data.forEach(function (bar, index) { var data = dataset.data[index]; myChart.fillText(data, bar._model.x, bar._model.y - 5); }); }); } } } }); Someone knows why?
Code was bit outdated, to add a percentage sign to the value you can just add it using string interpolation in the fillText method. Working sample: let myChart = document.getElementById('chartJSContainer').getContext('2d'); const label = ['A', 'B', 'C', 'D', 'E']; const datas = [85, 90, 53, 100, 76]; const backgroundColors = [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)' ]; const borderColors = [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)' ] let iChart = new Chart(myChart, { type: 'bar', data: { labels: label, datasets: [{ label: 'EQA-Übereinstimmung', data: datas, backgroundColor: backgroundColors, borderColor: borderColors, borderWidth: 1 }] }, options: { responsive: true, maintainAspectRatio: false, animation: { duration: 1, onComplete: (x) => { const chart = x.chart; var { ctx } = chart; ctx.textAlign = 'center'; ctx.fillStyle = "rgba(0, 0, 0, 1)"; ctx.textBaseline = 'bottom'; // Loop through each data in the datasets const metaFunc = this.getDatasetMeta; chart.data.datasets.forEach((dataset, i) => { var meta = chart.getDatasetMeta(i); meta.data.forEach((bar, index) => { var data = dataset.data[index]; ctx.fillText(`${data}%`, bar.x, bar.y - 5); }); }); } } } }); <body> <canvas id="chartJSContainer" width="600" height="400"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.js"></script> </body>
How to display the more then one value inside tooltip in bar chart.js?
I am using chart.js. I am sharing one example below. When I hover on the bar then I am getting tooltip with total votes. Now my concern is, Is it possible to display more than one value inside the tooltip. As of now it is displaying #of Votes 5. I have displayed the one more like Amount 40. I tried below code but it's not working. data: [[12, 19, 3, 5, 2, 3],[10, 20, 30, 40, 50, 60]], var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], //data: [[12, 19, 3, 5, 2, 3],[10, 20, 30, 40, 50, 60]], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); .innerbox { width: 600px; height: 300px; } <div class="innerbox"> <canvas id="myChart" width="400" height="300"></canvas> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
You can use the callback function afterLabel to display the second value like this: var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] }, tooltips: { callbacks: { afterLabel: function(tooltipItem, data) { var amount = [10, 20, 30, 40, 50, 60]; return "Amount " + amount[tooltipItem['index']]; } } } } }); .innerbox { width: 600px; height: 300px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script> <div class="innerbox"> <canvas id="myChart" width="400" height="300"></canvas> </div>
Is it possible to create just header tip visible bar chart with chart js just like in image
I want to change bar graph to make it look like the image one, which has only header tip visible not the whole bar, the header has the detail like shown in the image and only the header visible as a line in graph var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["2015-01", "2015-02", "2015-03"], datasets: [{ label: '# of Tomatoes', data: [12, 19, 13], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)' ], borderWidth: 1 }] }, options: { responsive: false, scales: { xAxes: [{ ticks: { maxRotation: 90, minRotation: 80 } }], yAxes: [{ ticks: { beginAtZero: true } }] } } }); body { background-color: #a3d5d3; } <canvas id="myChart" height="200"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.js"></script>
If you just want to display a dash for each value, you better choose a scatter chart and define dataset.pointStyle as 'line'. For scatter charts, no labels are defined but the data must be passed as objects containing x and y properties. Your xAxes would then have to be defined as a time cartesian axis. Note that Chart.js internally uses Moment.js for the functionality of the time axis. Therefore you should use the bundled version of Chart.js that includes Moment.js in a single file. The following code illustrates how it can be done. var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'scatter', data: { datasets: [{ label: '# of Tomatoes', data: [ { x: "2015-01", y: 12 }, { x: "2015-02", y: 19 }, { x: "2015-03", y: 3 }, { x: "2015-04", y: 5 }, { x: "2015-05", y: 2 }, { x: "2015-06", y: 3 }, { x: "2015-07", y: 20 }, { x: "2015-08", y: 3 }, { x: "2015-09", y: 5 }, { x: "2015-10", y: 6 }, { x: "2015-11", y: 2 }, { x: "2015-12", y: 1 } ], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)', 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], pointStyle: 'line', pointRadius: 10, pointHoverRadius: 10 }] }, options: { responsive: false, scales: { xAxes: [{ offset: true, type: 'time', time: { unit: 'month', displayFormats: { month: 'YYYY-MM' }, tooltipFormat: 'YYYY-MM' }, ticks: { maxRotation: 90, minRotation: 80 }, gridLines: { offsetGridLines: true } }], yAxes: [{ ticks: { beginAtZero: true } }] } } }); body { background-color: #a3d5d3; } <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script> <canvas id="myChart" height="200"></canvas>
If I correctly understand your question, you need floating bars, which are officially available since Chart.js v2.9.0. The feature was merged into chartjs:master with pull request #6056. Individual bars can now be specified with the syntax [min, max]. var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["2015-01", "2015-02", "2015-03", "2015-04", "2015-05", "2015-06", "2015-07", "2015-08", "2015-09", "2015-10", "2015-11", "2015-12"], datasets: [{ label: '# of Tomatoes', data: [[11,12], [18,19], [2,3], [4,5], [1,2], [2,3], [19,20], [2,3], [4,5], [5,6], [1,2], [0,1]], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)', 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { responsive: false, scales: { xAxes: [{ ticks: { maxRotation: 90, minRotation: 80 } }], yAxes: [{ ticks: { beginAtZero: true } }] } } }); body { background-color: #a3d5d3; } <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <canvas id="myChart" height="200"></canvas>
How to make money format in chart js in javascript
Above is my data in a chart bar using javascript, I didn't have any idea how to format the money like: "11,372,626" in the labels. This below is how to show the data in the chart bar. $scope.listData = response.data.respone; //all of my Json Data let myLabels = []; //For label let myDataset = []; //for money label for(let i = 0; i< $scope.listData.length; i++) { //looping the datas myLabels.push($scope.listData[i].period); myDataset.push($scope.listData[i].sales); } var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: myLabels, datasets: [{ label: 'Sales Store', // data: [12, 19, 3, 5, 2, 3], data: myDataset, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)', 'rgba(255, 159, 64, 1)', 'rgba(255, 159, 64, 1)', 'rgba(255, 159, 64, 1)', 'rgba(255, 159, 64, 1)', 'rgba(255, 159, 64, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero:false } }] } } }); The data is coming from an API in json format, how to format the money data so it can be shown in the labels?
You can try this: const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', }); ... options: { tooltips: { callbacks: { label: function(tooltipItem, data) { return formatter.format(tooltipItem.yLabel); }, }, }, }, example
How can I show texts only if they fit in the arc in Chart.Js 2.8.0?
I have a doughnut chart in Chart.Js with the chartjs-plugin-datalabels enabled. How can I write the string into the segments only if they fit into the segment of the chart? At the moment, my code looks like this: let ctx = document.getElementById("myChart"); let myChart = new Chart(ctx, { plugins: [ChartDataLabels], type: 'doughnut', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 0.3, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { plugins: { datalabels: { formatter: function(value) { return value + " kWh"; } } }, rotation: 1 * Math.PI, circumference: 1 * Math.PI } }); <body> <canvas id="myChart" width="400" height="400"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.6.0"></script> </body> The following image shows my problem:
May be this can work? Only adding a label when the value is above a certain threshold? let data = [12, 19, 3, 5, 0.3, 3]; let sum = 0; for (var i = 0; i < data.length; i++) { sum += data[i] } let ctx = document.getElementById("myChart"); let myChart = new Chart(ctx, { plugins: [ChartDataLabels], type: 'doughnut', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: data, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { plugins: { datalabels: { formatter: function(value) { percentage = (value / sum) * 100; if (percentage < 1) { return ""; } return value + " kWh"; } } }, rotation: 1 * Math.PI, circumference: 1 * Math.PI } }); <body> <canvas id="myChart" width="400" height="400"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.6.0"></script> </body>