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) {
//
}
});
});
Related
so I'm generating charts with a database and displaying them with JSON script and it works fine but the chart only displays when I click an option value, what I'm trying to do now is set a default value option for when the website opens it displays a default chart if that makes sense, below is my chart.js code.
function renderHtmlChart(){
$(document).ready(function (){
var selection= document.getElementById('YEAR').value;
var link = "https://udon.ads.ntu.ac.uk/web/itec30151/N0773065/new/data.php?YEAR='"+selection+"'";
$.ajax({
url: link,
method: "GET",
success: function(data=this.responseText) {
console.log(data);
var Destination = [];
var Bookings = [];
for(var i in data) {
Destination.push(data[i].Destination);
Bookings.push(data[i].Bookings);
}
createChart(Destination,Bookings,selection)
},
error: function(data) {
console.log(data);
}
});
});
}
function createChart(Destination,Bookings,selection){
var universalOptions = {
maintainAspectRatio: true,
responsive: false,
title: {
display: true,
text: 'Top 5 Flight Bookings'
},
legend: {
display: true,
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
scaleLabel: {
display: true,
labelString: 'Bookings'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Destinations'
}
}],
}
}
var chartdata = {
labels: Destination,
datasets : [
{
label: selection,
data: Bookings,
backgroundColor: ["#3366cc","#dc3912","#ff9900","#109618","#990099"],
borderWidth: '1',
borderColour: 'grey',
hoverBorderColor: 'black',
fill: false,
pointRadius: 0,
}
]
};
//stop overlap
$('select').on('change',function(){
barGraph.destroy();
});
// this makes legend hidden
var update_caption = function(legend) {
labels[legend.text] = legend.hidden;
var selected = Object.keys(labels).filter(function(key) {
return labels[key];
});
};
//this creates new graph
var ctx = document.getElementById('myChart');
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: universalOptions,
responsive: false,
});
}
hope you have latest version of jquery like:-
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
hope this will help
//create renderHtmlChart function
function renderHtmlChart()
{
var selection= document.getElementById('YEAR').value;
var link = "https://udon.ads.ntu.ac.uk/web/itec30151/N0773065/new/data.php?YEAR='"+selection+"'";
$.ajax({
url: link,
method: "GET",
success: function(data=this.responseText)
{
console.log(data);
var Destination = [];
var Bookings = [];
for(var i in data)
{
Destination.push(data[i].Destination);
Bookings.push(data[i].Bookings);
}
createChart(Destination,Bookings,selection)
},
error: function(data)
{
console.log(data);
}
});
}
//create createChart function
function createChart(Destination,Bookings,selection)
{
var universalOptions =
{
maintainAspectRatio: true,
responsive: false,
title:
{
display: true,
text: 'Top 5 Flight Bookings'
},
legend:
{
display: true,
},
scales:
{
yAxes: [{
ticks: {
beginAtZero: true,
},
scaleLabel: {
display: true,
labelString: 'Bookings'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Destinations'
}
}],
}
}
var chartdata = {
labels: Destination,
datasets : [
{
label: selection,
data: Bookings,
backgroundColor: ["#3366cc","#dc3912","#ff9900","#109618","#990099"],
borderWidth: '1',
borderColour: 'grey',
hoverBorderColor: 'black',
fill: false,
pointRadius: 0,
}
]
};
// this makes legend hidden
var update_caption = function(legend) {
labels[legend.text] = legend.hidden;
var selected = Object.keys(labels).filter(function(key) {
return labels[key];
});
};
//this creates new graph
var ctx = document.getElementById('myChart');
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: universalOptions,
responsive: false,
});
}
$(funtion(){
//onload call renderHtmlChart function
renderHtmlChart();
//on select input change call renderHtmlChart function
$('select').on('change',function(){
renderHtmlChart();
});
})
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);
}
});
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 ?
The documentation for time in ChartJs is extremely vague and gives little working examples so I'm struggling to get a time series working for temperature data recorded at a particular time. I can get the correct time format to appear in the tooltip, but it will not appear on the X axis.
Graph code:
<script>
var ctx = document.getElementById('myChart');
var data = {
labels: [],
datasets: [{
label: "Temperature Graph",
fill: false,
borderColor: '#3cba9f',
data: []
}]
}
const options = {
type: 'line',
data: data,
options: {
fill: false,
responsive: true,
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
stepSize: 1,
displayFormats: {
day: 'MMM D'
}
},
display: true,
scaleLabel: {
display: true,
labelString: "Date",
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
},
display: true,
scaleLabel: {
display: true,
labelString: "Temperature",
}
}]
}
}
}
var chart = new Chart(ctx, options)
</script>
Data collection code:
window.onload = function load() {
getData();
}
var prevData = [];
var prevLabels = [];
function getData() {
var xhr = new XMLHttpRequest();
xhr.open('GET', encodeURI('http://localhostlocalhost/getTemp'));
xhr.onload = function() {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data);
var label = data.timestamp * 1000;
prevData.push(data.temperature);
prevLabels.push(label);
chart.data.datasets[0].data = prevData;
chart.data.labels = prevLabels;
chart.update();
}
else {
alert(xhr.status);
}
};
xhr.send();
setTimeout(getData, 10000);
}
Example xhr response:
{temperature: 17, humidity: 38, location: "location", timestamp: 1542824305}
The data is plotted to the graph and all works as expected, the time just does not appear on the X axis
I am trying to implement an Angular horizontal stacked bar chart- Something like this example.
However, I want just one bar that is stacked.
I am working with AngularJS and Chart.js. I have the example showing on the page.
In the PieController, ChartData contains:
{"data":["63","38"],"labels":["Ford","GM"]}
In the example, instead of the label on the outside, I would like the label and then the number to be inside the chart. Like [=====Ford 63====|===GM 38===] the equals represent bar colors. There will be more data points than the current two.
Here is my page
<div ng-controller="PieController">
data {{ChartData}} //testing purposes
<div ng-init="getBarChart()">
<canvas id="Chart1"></canvas>
</div>
Here is my JavaScript controller
app.controller('PieController', function($scope, ChartService) {
$scope.getBarChart = function(){
ChartService.get({name: 'main'}, function(data) {
$scope.ChartData = data;
var barOptions_stacked = {
tooltips: {
enabled: false
},
hover: {
animationDuration: 0
},
scales: {
xAxes: [{
ticks: {
beginAtZero: true,
fontFamily: "'Open Sans Bold', sans-serif",
fontSize: 11
},
scaleLabel: {
display: false
},
gridLines: {},
stacked: true
}],
yAxes: [{
gridLines: {
display: false,
color: "#fff",
zeroLineColor: "#fff",
zeroLineWidth: 0
},
ticks: {
fontFamily: "'Open Sans Bold', sans-serif",
fontSize: 11
},
stacked: true
}]
},
legend: {
display: false
},
animation: {
onComplete: function () {
var chartInstance = this.chart;
var ctx = chartInstance.ctx;
ctx.textAlign = "left";
ctx.font = "9px Open Sans";
ctx.fillStyle = "#fff";
Chart.helpers.each(this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
Chart.helpers.each(meta.data.forEach(function (bar, index) {
data = dataset.data[index];
if (i == 0) {
ctx.fillText(data, 50, bar._model.y + 4);
} else {
ctx.fillText(data, bar._model.x - 25, bar._model.y + 4);
}
}), this)
}), this);
}
},
pointLabelFontFamily: "Quadon Extra Bold",
scaleFontFamily: "Quadon Extra Bold",
};
var ctx = document.getElementById("Chart1");
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ["2014", "2013", "2012", "2011"],
datasets: [{
data: [727, 589, 537, 543, 574],
backgroundColor: "rgba(63,103,126,1)",
hoverBackgroundColor: "rgba(50,90,100,1)"
}, {
data: [238, 553, 746, 884, 903],
backgroundColor: "rgba(163,103,126,1)",
hoverBackgroundColor: "rgba(140,85,100,1)"
}, {
data: [1238, 553, 746, 884, 903],
backgroundColor: "rgba(63,203,226,1)",
hoverBackgroundColor: "rgba(46,185,235,1)"
}]
},
options: barOptions_stacked,
})
});//end chat service.get
}
});
Instead of hard coding in the dataset which is what its doing now, is there a way I can use the data "ChartData" that I outlined in the beginning of the post?
I'm not sure how to do it or if its even possible.
In order to get the label to show in the bar, reference the labels property of $scope.ChartData:
ctx.fillText($scope.ChartData.labels[index] +" "+ data, 50, bar._model.y + 4);
Instead of hard coding in the dataset which is what its doing now, is there a way I can use the data "ChartData" that I outlined in the beginning of the post?
Use properties from the data variable (supplied by the ChartService get function) i.e. data.labels and data.data instead of the hard-coded values.
So update the labels line from:
labels: ["2014", "2013", "2012", "2011"],
To this:
labels: data.labels,
And similarly for the datasets:
datasets: [{
data: data.data,
So when creating the Chart it should look like this:
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: data.labels,
datasets: [{
data: data.data,
backgroundColor: "rgba(63,103,126,1)",
hoverBackgroundColor: "rgba(50,90,100,1)"
}]
},
options: barOptions_stacked,
});
Expand the code snippet below for a demonstration.
Note: there is currently an issue with the resize-listener, blocked by a CORS issue - I am trying to find a way to disable that.
Update:
Per your comment about stacking the bars (horizontally) - yes that is possible. Just have one element in the datasets array for each item. One simple way to have this is to use Array.map() to create an array similar to the example:
var bgColors = [
"rgba(63,103,126,1)",
"rgba(50,90,100,1)"
];
var hoverBgColors = [
"rgba(50,90,100,1)",
"rgba(140,85,100,1)"
];
var datasets = data.data.map(function(value, index) {
return {
data: [value],
backgroundColor: bgColors[index],
hoverBackgroundColor: hoverBgColors[index]
}
});
Then use variable datasets when creating the Chart object:
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: data.labels,
datasets: datasets
},
options: barOptions_stacked,
});
Also, there is some weird math going on for the location of the second label but the helper function can be updated like below (I tried dividing the x value by 75 but that may need to be adjusted - I am not sure what "appropriate" values are for that ...):
if (i == 0) {
ctx.fillText($scope.ChartData.labels[i] + " " + data, 50, bar._model.y + 4);
} else {
ctx.fillText($scope.ChartData.labels[i] + " " + data, (bar._model.x - 25) / 75, bar._model.y + 4);
}
var app = angular.module('myApp', []);
app.factory('ChartService', function() {
return { //dummy chart service
get: function(obj, callback) {
var data = {
"data": ["63", "38"],
"labels": ["Ford", "GM"]
};
callback(data);
}
};
});
app.controller('PieController', function($scope, ChartService) {
$scope.getBarChart = function() {
ChartService.get({
name: 'main'
}, function(data) {
$scope.ChartData = data;
var barOptions_stacked = {
tooltips: {
enabled: false
},
hover: {
animationDuration: 0
},
scales: {
xAxes: [{
ticks: {
beginAtZero: true,
fontFamily: "'Open Sans Bold', sans-serif",
fontSize: 11
},
scaleLabel: {
display: false
},
gridLines: {},
stacked: true
}],
yAxes: [{
gridLines: {
display: false,
color: "#fff",
zeroLineColor: "#fff",
zeroLineWidth: 0
},
ticks: {
fontFamily: "'Open Sans Bold', sans-serif",
fontSize: 11
},
stacked: true
}]
},
legend: {
display: false
},
animation: {
onComplete: function() {
var chartInstance = this.chart;
var ctx = chartInstance.ctx;
ctx.textAlign = "left";
ctx.font = "9px Open Sans";
ctx.fillStyle = "#fff";
Chart.helpers.each(this.data.datasets.forEach(function(dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
Chart.helpers.each(meta.data.forEach(function(bar, index) {
data = dataset.data[index];
if (i == 0) {
ctx.fillText($scope.ChartData.labels[i] + " " + data, 50, bar._model.y + 4);
} else {
ctx.fillText($scope.ChartData.labels[i] + " " + data, (bar._model.x - 25) / 75, bar._model.y + 4);
}
}), this)
}), this);
}
},
pointLabelFontFamily: "Quadon Extra Bold",
scaleFontFamily: "Quadon Extra Bold",
};
var ctx = document.getElementById("Chart1");
var bgColors = [
"rgba(63,103,126,1)",
"rgba(50,90,100,1)"
];
var hoverBgColors = [
"rgba(50,90,100,1)",
"rgba(140,85,100,1)"
];
var datasets = data.data.map(function(value, index) {
return {
data: [value],
backgroundColor: bgColors[index],
hoverBackgroundColor: hoverBgColors[index]
}
});
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
//use empty labels because the labels are on the bars
labels: data.labels.map(function() {
return '';
}),
datasets: datasets
},
options: barOptions_stacked,
})
}); //end chat service.get
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="PieController">
data {{ChartData}} //testing purposes
<div ng-init="getBarChart()">
<canvas id="Chart1"></canvas>