Download or Export Chart.js data to CSV - javascript

I have API data from https://gmlews.com/api/data . And I plot the data for accelero_x on the chart.js like this :
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$("#firstdatepicker").datepicker();
$("#lastdatepicker").datepicker();
$("#filter").click(function() {
var from_date = $("#firstdatepicker").val();
var to_date = $("#lastdatepicker").val();
if (from_date != '' && to_date != '') {
console.log(from_date, to_date);
var endpoint = '/api/data';
$.ajax({
method: "GET",
url: endpoint,
data: {
from_date: from_date,
to_date: to_date
},
success: function(data){
console.log(data); //get all data
//get data by fields
var accelero_x = [], time = [];
for (var i=0; i<data.length; i++){
accelero_x.push(data[i].accelero_x);
time.push(data[i].timestamp);
}
console.log(accelero_x);
console.log(time);
//plot the chart
var ctx = document.getElementById("acceleroxChart").getContext('2d');
var acceleroxChart = new Chart(ctx, {
type: 'line',
data: {
labels: time,
datasets: [{
label: 'Accelero-x (mV/g)',
data: accelero_x,
fill: false,
borderColor: "#80b6f4",
pointBorderColor: "#80b6f4",
pointBackgroundColor: "#80b6f4",
pointHoverBackgroundColor: "#80b6f4",
pointHoverBorderColor: "#80b6f4",
pointBorderWidth: 10,
pointHoverRadius: 10,
pointHoverBorderWidth: 1,
pointRadius: 1,
borderWidth: 4,
}]
},
options: {
reponsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero:false,
stepSize:0.5
},
scaleLabel: {
display: true,
labelString: 'Accelero sb.x (mV/g)'
}
}],
xAxes: [{
display: true,
type: "time",
time: {
minUnit: "hour",
unit: "hour",
unitStepSize: 6,
min: moment(from_date).toDate(),//Date object type
max: moment(to_date).toDate()//Date object type
},
scaleLabel: {
display: true,
labelString: 'Time'
}
}]
}
}
});
},
error: function(error_data){
console.log(error_data)
}
});
} else {
alert("Please Select Date");
}
});
});
The problem is how can I download/export data from the graph to CSV? The data that will appear on CSV are datetime and the value of accelero_x, I am a newbie programmer. I hope anyone can help me with the code.

It looks like this link does what you're looking for, just with canvasjs. I adapted it here for ChartJS:
Here's the relevant code:
const dataLabels = ['Jan', 'Feb', 'March', 'April', 'May', 'June', 'July'];
const data = {
labels: dataLabels,
datasets: [{
label: 'Dataset 1',
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: [
'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(54, 162, 235, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(201, 203, 207, 0.2)'
],
borderColor: [
'rgb(255, 99, 132)',
'rgb(255, 159, 64)',
'rgb(255, 205, 86)',
'rgb(75, 192, 192)',
'rgb(54, 162, 235)',
'rgb(153, 102, 255)',
'rgb(201, 203, 207)'
],
borderWidth: 1
},
{
label: 'Dataset 2',
data: [55, 69, 70, 61, 66, 45, 50],
backgroundColor: [
'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(54, 162, 235, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(201, 203, 207, 0.2)'
],
borderColor: [
'rgb(255, 99, 132)',
'rgb(255, 159, 64)',
'rgb(255, 205, 86)',
'rgb(75, 192, 192)',
'rgb(54, 162, 235)',
'rgb(153, 102, 255)',
'rgb(201, 203, 207)'
],
borderWidth: 1
}
]
};
const config = {
type: 'bar',
data: data,
options: {
scales: {
y: {
beginAtZero: true
}
}
},
};
var chart = new Chart(document.getElementById('chartContainer'), config);
document.getElementById("downloadCSV").addEventListener("click", function() {
downloadCSV({
filename: "chart-data.csv",
chart: chart
})
});
function convertChartDataToCSV(args) {
let result, columnDelimiter, lineDelimiter, labels, data;
data = args.data.data || null;
if (data == null || !data.length) {
return null;
}
labels = args.labels || null;
if (labels == null || !labels.length) {
return null;
}
columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n';
result = '' + columnDelimiter;
result += labels.join(columnDelimiter);
result += lineDelimiter;
result += args.data.label.toString();
for (let i = 0; i < data.length; i++) {
result += columnDelimiter;
result += data[i];
}
result += lineDelimiter;
return result;
}
function downloadCSV(args) {
var data, filename, link;
var csv = "";
for (var i = 0; i < chart.data.datasets.length; i++) {
csv += convertChartDataToCSV({
data: chart.data.datasets[i],
labels: dataLabels
});
}
if (csv == null) return;
console.log(csv);
filename = args.filename || 'chart-data.csv';
if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
// not sure if anything below this comment works
data = encodeURI(csv);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
document.body.appendChild(link); // Required for FF
link.click();
document.body.removeChild(link);
}
<script src=" https://cdn.jsdelivr.net/npm/chart.js#4.2.0/dist/chart.umd.min.js "></script>
<canvas id="chartContainer" style="height: 360px; width: 100%;"></canvas>
<button id="downloadCSV">Download Chart Data as CSV</button>

Related

How to show Label with each line in Chart.js v3? [duplicate]

This question already has an answer here:
How do I show labels along with lines in Chart.js v3? [duplicate]
(1 answer)
Closed last month.
Like this one:
The label property in datasets is not working and shows nothing:
datasets: [{
label: 'Line 1',
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2
},
{
label: 'Line 2',
data: [28, 48, 40, 19, 86, 27, 90],
backgroundColor: 'rgba(153, 102, 255, 0.2)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 2
}]
},
The complete code is given below:
<!DOCTYPE html>
<html>
<head>
<title> Example</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.1/chart.min.js"></script>
</head>
<body>
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Line 1',
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2
},
{
label: 'Line 2',
data: [28, 48, 40, 19, 86, 27, 90],
backgroundColor: 'rgba(153, 102, 255, 0.2)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 2
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
},
legend: {
display: false
}
}
});
</script>
</body>
</html>
Well if a plugin like https://www.chartjs.org/chartjs-plugin-annotation/2.0.0/ doesn't solve the problem (Check out this answer for a demo), I would write my own specific plugin, that draws on the chart, after rendering was completed (see demo below for details).
And to be on the save side, I would add some padding to the right of the chart, to prevent a cut off, as done in the demo (link to the documentation).
Here a demo, how a very basic plugin could like:
(chart data from the question)
var miniLabelPlugin = {
id: 'miniLabelPlugin',
afterRender: function(chart, args, options) {
const { ctx } = chart;
chart.config.data.datasets.forEach((dataSet, index) => {
let lastPoint = chart.getDatasetMeta(index).data[chart.getDatasetMeta(index).data.length - 1];
let lastValue = dataSet.data[dataSet.data.length -1]
console.info(dataSet.data, lastPoint)
ctx.fillStyle = options.textColor;
ctx.font = options.font;
ctx.fillText(`${lastValue}`, lastPoint.x + options.paddingLeft, lastPoint.y);
});
},
defaults: {
paddingLeft: 10,
font: "10px Arial",
textColor: "black"
}
}
const config ={
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Line 1',
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2
},
{
label: 'Line 2',
data: [28, 48, 40, 19, 86, 27, 90],
backgroundColor: 'rgba(153, 102, 255, 0.2)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 2
}]
},
// here the plugin is added to the chart
plugins: [miniLabelPlugin],
options: {
scales: {
y: {
beginAtZero: true
}
},
plugins:{
legend: {
display: false
},
},
layout: {
padding: {
right: 50
}
}
}
};
new Chart(
document.getElementById('chart'),
config
);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>
<div class="chart" style="height:184px; width:350px;">
<canvas id="chart" ></canvas>
</div>
For static labels you need to add "animation" key like
import {
Chart,
Sample
} from "chart.js";
import {
map
} from "lodash";
import {
data
} from "../data";
var ctx = document.getElementById("myChart");
const d = map(data, (data, index) => {
return {
data: [data],
backgroundColor: "blue",
pointRadius: 2,
fill: "start"
};
});
const dd = map(data, data => {
return data.y;
});
console.log(dd);
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Line 1',
data: [6, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2
},
{
label: 'Line 2',
data: [5, 20, 40, 19, 86, 27, 90],
backgroundColor: 'rgba(153, 102, 255, 0.2)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 2
}
]
},
options: {
animation: {
onComplete: function() {
const chartInstance = myChart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(
18,
Chart.defaults.global.defaultFontStyle,
Chart.defaults.global.defaultFontFamily
);
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.data.datasets.forEach(function(dataset, i) {
const meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
const data = dataset.data[index];
ctx.fillStyle = "#000";
ctx.fillText(data, bar._model.x, bar._model.y - 2);
});
});
}
},
tooltips: {
enabled: true
},
scales: {
y: {
beginAtZero: true
}
},
legend: {
display: false
}
}
});
Goodluck!

How to create a chart with chartjs.org with data from an array?

I try to create a website with a bar-chart on it. I like to use ChartJs.
There are some good examples, but I don't know how to visualise the data if the data is an array.
var myArray = [{
year: '2016',
value: 5
},
{
year: '2017',
value: 9
},
{
year: '2018',
value: 4
}
];
How do I loop throu myArray to create a bar chart like this one in the example?
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['2016', '2017', '2018'],
datasets: [{
label: '# of Votes',
data: [5, 9, 4],
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
}
}]
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Thanks for your help!
Best, Marius
You can map your array of objects, getting only the value you need.
I did it by var values = myArray.map((x) => x.value) and then using values as the value to the data property inside chart options.
For the labels, you can use the same logic, but with x.year.
Below code represents an example:
var myArray = [{
year: '2016',
value: 5
},
{
year: '2017',
value: 9
},
{
year: '2018',
value: 4
}
];
//FILTER THE VALUES
var values = myArray.map((x) => x.value)
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['2016', '2017', '2018'],
datasets: [{
label: '# of Votes',
data: values,
borderWidth: 1,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)'
],
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="300" height="150"></canvas>
If, for some reason (browser maybe), you cant use arrow functions, then go with:
var values = myArray.map(function(x) {return x.value})

ChartJS: Get value from another another Chart

I have two charts, First chart shows the breakup of Shirt sales.
Second is the comparison of Blue Shirt vs Blue Trouser sales.
I want to import the Blue Shirt value from the first Chart to Second chart.
Here is the Code with two charts:
var ctx = document.getElementById("myChart1").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: 'Shirts',
data: [10, 10, 15, 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
}
}]
},
}
});
var ctx = document.getElementById("myChart2").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Blue Shirts", "Blue Trousers"],
datasets: [{
label: 'Sales',
data: [10, 8],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
}
});
Here is the JSFiddle (https://jsfiddle.net/kingBethal/L8x790fn/15/).
I found this thread describing getting data from click events: Click events on Pie Charts in Chart.js
I made also made a new fiddle here where it logs a chart object containing the chart data on chart click: https://jsfiddle.net/btnL9d2a/16/
myChart1Canvas.onclick = function(evt) {
var activePoints = myChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
// `chartData` will be an object in the format {'Labels' : Array, 'datasets' : Array}.
console.log(chartData);
}
};
chartData.datasets[0].data is an array of the clicked-on chart's data.

How to get the angularjs scope variable data to the chartjs data

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.

Chart.js piechart, only have border on the outside of arc

I have a pie chart made with chart.js and currently i'm wondering if its possible to only have a border for the outside of the circle / arc like so:
I tried the following configurations but it applies border the to the whole segment.
options: {
elements: {
arc: {
borderWidth: 0
}
}
}
and also:
data: {
datasets: [{
data: [male_data , female_data],
backgroundColor: pieColors1,
borderWidth: [10, 0, 0, 0, 0]
}]
},
but this is what im getting:
I guess you have to create your own color image (Solid color with white strip on top) and pass it in as a canvas image.
Below is a modified example I've made based on the sample given from the chart.js documentation and a random picture found on the net.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0/Chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var img = new Image();
img.src = 'http://www.worktop-express.co.uk/media/gbu0/metro-tiles-white-sparkle-worktops-100717.jpg';
img.onload = function() {
var ctx = document.getElementById("myChart").getContext('2d');
var fillPattern = ctx.createPattern(img, 'repeat');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 10)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
fillPattern
],
borderColor: [
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)'
],
borderWidth: 0
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0/Chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var img = new Image();
img.src = 'http://www.worktop-express.co.uk/media/gbu0/metro-tiles-white-sparkle-worktops-100717.jpg';
img.onload = function() {
var ctx = document.getElementById("myChart").getContext('2d');
var fillPattern = ctx.createPattern(img, 'repeat');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 10)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
fillPattern
],
borderColor: [
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
</script>

Categories

Resources