Chart.js stacked and grouped bar chart - javascript

is there any way to do a stacked and grouped bar chart with Chart.js library?
It should look something like this http://www.highcharts.com/demo/column-stacked-and-grouped

OK, I found the solution. It's described in this GitHub issue and solution is in this JSFiddle
Chart.defaults.groupableBar = Chart.helpers.clone(Chart.defaults.bar);
var helpers = Chart.helpers;
Chart.controllers.groupableBar = Chart.controllers.bar.extend({
calculateBarX: function (index, datasetIndex) {
// position the bars based on the stack index
var stackIndex = this.getMeta().stackIndex;
return Chart.controllers.bar.prototype.calculateBarX.apply(this, [index, stackIndex]);
},
hideOtherStacks: function (datasetIndex) {
var meta = this.getMeta();
var stackIndex = meta.stackIndex;
this.hiddens = [];
for (var i = 0; i < datasetIndex; i++) {
var dsMeta = this.chart.getDatasetMeta(i);
if (dsMeta.stackIndex !== stackIndex) {
this.hiddens.push(dsMeta.hidden);
dsMeta.hidden = true;
}
}
},
unhideOtherStacks: function (datasetIndex) {
var meta = this.getMeta();
var stackIndex = meta.stackIndex;
for (var i = 0; i < datasetIndex; i++) {
var dsMeta = this.chart.getDatasetMeta(i);
if (dsMeta.stackIndex !== stackIndex) {
dsMeta.hidden = this.hiddens.unshift();
}
}
},
calculateBarY: function (index, datasetIndex) {
this.hideOtherStacks(datasetIndex);
var barY = Chart.controllers.bar.prototype.calculateBarY.apply(this, [index, datasetIndex]);
this.unhideOtherStacks(datasetIndex);
return barY;
},
calculateBarBase: function (datasetIndex, index) {
this.hideOtherStacks(datasetIndex);
var barBase = Chart.controllers.bar.prototype.calculateBarBase.apply(this, [datasetIndex, index]);
this.unhideOtherStacks(datasetIndex);
return barBase;
},
getBarCount: function () {
var stacks = [];
// put the stack index in the dataset meta
Chart.helpers.each(this.chart.data.datasets, function (dataset, datasetIndex) {
var meta = this.chart.getDatasetMeta(datasetIndex);
if (meta.bar && this.chart.isDatasetVisible(datasetIndex)) {
var stackIndex = stacks.indexOf(dataset.stack);
if (stackIndex === -1) {
stackIndex = stacks.length;
stacks.push(dataset.stack);
}
meta.stackIndex = stackIndex;
}
}, this);
this.getMeta().stacks = stacks;
return stacks.length;
},
});
var data = {
labels: ["January", "February", "March"],
datasets: [
{
label: "Apples",
backgroundColor: "rgba(99,255,132,0.2)",
data: [20, 10, 30],
stack: 1
},
{
label: "Bananas",
backgroundColor: "rgba(99,132,255,0.2)",
data: [40, 50, 20],
stack: 1
},
{
label: "Cookies",
backgroundColor: "rgba(255,99,132,0.2)",
data: [60, 20, 20],
stack: 1
},
{
label: "Apples",
backgroundColor: "rgba(99,255,132,0.2)",
data: [20, 10, 30],
stack: 2
},
{
label: "Bananas",
backgroundColor: "rgba(99,132,255,0.2)",
data: [40, 50, 20],
stack: 2
},
{
label: "Cookies",
backgroundColor: "rgba(255,99,132,0.2)",
data: [60, 20, 20],
stack: 2
},
{
label: "Apples",
backgroundColor: "rgba(99,255,132,0.2)",
data: [20, 10, 30],
stack: 3
},
{
label: "Bananas",
backgroundColor: "rgba(99,132,255,0.2)",
data: [40, 50, 20],
stack: 3
},
{
label: "Cookies",
backgroundColor: "rgba(255,99,132,0.2)",
data: [60, 20, 20],
stack: 3
},
]
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, {
type: 'groupableBar',
data: data,
options: {
legend: {
labels: {
generateLabels: function(chart) {
return Chart.defaults.global.legend.labels.generateLabels.apply(this, [chart]).filter(function(item, i){
return i <= 2;
});
}
}
},
scales: {
yAxes: [{
ticks: {
max: 160,
},
stacked: true,
}]
}
}
});

You should use the stack property of the dataset object for each dataset.
As you can see in Chart.js Documentation, stack is defined as:
"The ID of the group to which this dataset belongs to (when stacked, each group will be a separate stack)"
I believe this functionality has been introduced recently and in 2016 Chart.js did not have this because of this post

You can acheive stacked bar chart with below data
this.dataStackedBarChart = {
type: 'horizontalBar',
labels: this.stackedBarChartLabel,
datasets: [
{
label: 'Success Count',
stack: 'Stack 0',
data: this.successCount,
backgroundColor: 'green'
},
{
label: 'FailureCount',
stack: 'Stack 0',
data: this.failureCount,
backgroundColor: 'red'
},
{
label: 'AvgDuration',
stack: 'Stack 1',
data: this.avgDuration,
backgroundColor: 'black'
},
{
label: 'MaxDuration',
stack: 'Stack 2',
data: this.maxDuration,
backgroundColor: 'orange'
},
{
label: 'MinDuration',
stack: 'Stack 3',
data: this.minDuration,
backgroundColor: 'pink'
}
],
borderWidth: 2
}
this.optionsStackedBarChart = {
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
var label = this.uniqueApiPath[tooltipItem.index];
return label;
}
}
},
scales: {
xAxes: [
{
stacked: true,
display: true,
ticks: {
beginAtZero: true,
min: 0,
suggestedMin: 0
}
}
],
yAxes: [
{
stacked: true,
display: true,
ticks: {
beginAtZero: true,
min: 0,
suggestedMin: 0
}
}
]
}

Related

How to disable converting decimal number to exponential?

window.chartColors = {
red: '#ffb5c5',
orange: '#FFA500',
yellow: '#F0E68C',
green: '#aee0e0',
blue: '#87CEFA',
purple: '#EE82EE',
grey: '#C0C0C0'
};
$(document).ready(function() {
var data = [{
"tc": "1.25173997",
"trf": "0.00000024",
"nc": "1.00139199",
"formatted_date": "temmp1",
"from_date": "2019-02-01 00:00:00",
"to_date": "2019-02-08 23:59:59"
}, ];
var formatted_date = [];
var tcs = [];
var trps = [];
var ncs = [];
// var data = $.parseJSON(data);
$.each(data, function(index, item) {
formatted_date.push(item.formatted_date);
tcs.push(item.tc);
trps.push(item.trf);
ncs.push(item.nc);
});
refData = [{
label: 'C',
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: tcs,
fill: false,
/* cubicInterpolationMode: 'monotone' */
},
{
label: 'R P',
backgroundColor: window.chartColors.red,
borderColor: window.chartColors.red,
data: trps,
fill: false
},
{
label: 'N C',
backgroundColor: window.chartColors.green,
borderColor: window.chartColors.green,
data: ncs,
fill: false
},
];
var chartdata = {
labels: formatted_date,
datasets: refData
};
//console.log(chartdata);
var graphTarget = $("#myChart");
var Graph = new Chart(graphTarget, {
type: 'line',
data: chartdata,
options: {
responsive: true,
title: {
display: true,
text: 'R P'
},
scales: {
xAxes: [{
// stacked: true,
display: true,
scaleLabel: {
display: true,
labelString: 'Duration'
}
}],
yAxes: [{
// stacked: true,
display: true,
scaleLabel: {
display: true,
labelString: 'Amt'
},
ticks: {
min: 0, // it is for ignoring negative step.
}
}]
},
},
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<div style="width:75%;">
<canvas id="myChart"></canvas>
</div>
As you can see for R P 0.00000024 is getting converted into 2.4e-7. But I want it show as is i.e. 0.00000024.
For other decimals numbers, it's perfectly fine, but for the above-mentioned decimal, it's converting into exponential. Is there any option to set? Is this possible?
With the help of this solution, I patched my problem. If anyone got better solution let me know.
Number.prototype.noExponents = function() {
var data = String(this).split(/[eE]/);
if (data.length == 1) return data[0];
var z = '',
sign = this < 0 ? '-' : '',
str = data[0].replace('.', ''),
mag = Number(data[1]) + 1;
if (mag < 0) {
z = sign + '0.';
while (mag++) z += '0';
return z + str.replace(/^\-/, '');
}
mag -= str.length;
while (mag--) z += '0';
return str + z;
}
window.chartColors = {
red: '#ffb5c5',
orange: '#FFA500',
yellow: '#F0E68C',
green: '#aee0e0',
blue: '#87CEFA',
purple: '#EE82EE',
grey: '#C0C0C0'
};
$(document).ready(function() {
var data = [{
"tc": "1.25173997",
"trf": "0.00000024",
"nc": "1.00139199",
"formatted_date": "temmp1",
"from_date": "2019-02-01 00:00:00",
"to_date": "2019-02-08 23:59:59"
}, ];
var formatted_date = [];
var tcs = [];
var trps = [];
var ncs = [];
// var data = $.parseJSON(data);
$.each(data, function(index, item) {
formatted_date.push(item.formatted_date);
tcs.push(item.tc);
trps.push(item.trf);
ncs.push(item.nc);
});
refData = [{
label: 'C',
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: tcs,
fill: false,
/* cubicInterpolationMode: 'monotone' */
},
{
label: 'R P',
backgroundColor: window.chartColors.red,
borderColor: window.chartColors.red,
data: trps,
fill: false
},
{
label: 'N C',
backgroundColor: window.chartColors.green,
borderColor: window.chartColors.green,
data: ncs,
fill: false
},
];
var chartdata = {
labels: formatted_date,
datasets: refData
};
//console.log(chartdata);
var graphTarget = $("#myChart");
var Graph = new Chart(graphTarget, {
type: 'line',
data: chartdata,
options: {
responsive: true,
title: {
display: true,
text: 'R P'
},
scales: {
xAxes: [{
// stacked: true,
display: true,
scaleLabel: {
display: true,
labelString: 'Duration'
}
}],
yAxes: [{
// stacked: true,
display: true,
scaleLabel: {
display: true,
labelString: 'Amt'
},
ticks: {
min: 0, // it is for ignoring negative step.
}
}]
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
label += tooltipItem.yLabel.noExponents();
return label;
}
}
}
},
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<div style="width:75%;">
<canvas id="myChart"></canvas>
</div>

Chart.js too slow rendering vertical stacked bars chart

I'm using chart.js API to render a several stacked vertical bars chart, but the performance is slow. I even made some changes such that all the content object was already processed by the server, and not the browser, but I realised the big majority of time comes from the final function new Chart(overallStatsChart, content);.
I also tried switching off animation, which slightly improved performance, but not that much.
Any ideas on how to improve performance, that is, initial loading?
var countryList = {"AR":"Argentina","AU":"Australia","BO":"Bolivia","BR":"Brasil","CA":"Canada","CL":"Chile","CN":"中国","CO":"Colombia","CR":"Costa Rica","CU":"Cuba","CZ":"Česká","DE":"Deutschland","DK":"Danmark","DO":"Rep. Dominicana","EC":"Ecuador","ES":"España","FI":"Suomessa","FR":"France","GR":"Ελλάδα","GT":"Guatemala","HU":"Magyarország","IE":"Ireland","IN":"India","IT":"Italia","JP":"日本","MX":"México","NI":"Nicaragua","NL":"Nederland","NO":"Norge","PA":"Panamá","PE":"Perú","PL":"Polska","PR":"Puerto Rico","PT":"Portugal","PY":"Paraguay","RO":"România","RU":"Россия","SE":"Sverige","SV":"El Salvador","TR":"Türkiye","UA":"Україна","UK":"United Kingdom","US":"USA","UY":"Uruguay","VE":"Venezuela"};
//populates country labels
var labels = [], size = 0;
for (var key in countryList){
labels.push(key);
size++;
}
var _data = function(i){
var arr = [];
for (var n=0; n<size; n++){
arr.push(n==i ? 1 : 0);
}
return arr;
};
var dataset = [], i=0;
for (var key in countryList){
dataset.push(
{
label: "depreciation",
data: _data(i),
backgroundColor: 'navy'
}, {
label: "insurance",
data: _data(i),
backgroundColor: 'blue'
}, {
label: "credit",
data: _data(i),
backgroundColor: 'aqua'
}, {
label: "inspection",
data: _data(i),
backgroundColor: 'teal'
}, {
label: "road taxes",
data: _data(i),
backgroundColor: 'olive'
}, {
label: "maintenance",
data: _data(i),
backgroundColor: 'green'
}, {
label: "repairs",
data: _data(i),
backgroundColor: 'lime'
}, {
label: "fuel",
data: _data(i),
backgroundColor: 'maroon'
}, {
label: "parking",
data: _data(i),
backgroundColor: 'yellow'
}, {
label: "tolls",
data: _data(i),
backgroundColor: 'orange'
}, {
label: "fines",
data: _data(i),
backgroundColor: 'red'
}, {
label: "washing",
data: _data(i),
backgroundColor: 'purple'
}, {
label: "maintenance",
data: _data(i),
backgroundColor: 'green'
}
);
i++;
}
var options = {
maintainAspectRatio: false,
legend: {
position: 'bottom', // place legend on the right side of chart
display: false, //do not display
labels : {
fontSize: 9,
fontColor: 'black'
}
},
scales: {
xAxes: [{
stacked: true, // this should be set to make the bars stacked
beginAtZero: true
}],
yAxes: [{
stacked: true, // this also..
beginAtZero: true
}]
},
animation: {
duration : 1000,
easing : 'linear'
}
};
var content = {
type: 'bar',
data: {
labels: labels,
datasets: dataset
},
options: options
};
//I made tests with timestamps and here it takes the biggest part of the time
new Chart(overallStatsChart, content);
.chart {
position: relative;
margin: auto;
}
#overallStatsChartDiv{
min-height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<div class="chart" id="overallStatsChartDiv">
<canvas id="overallStatsChart"></canvas>
</div>
Now I get it :)
I was wrongly duplicating the data attributes, based on this answer.
Solution is quite simple, every data attribute can have directly all the values, without the need of introduction of zeros.
var countryList = {"AR":"Argentina","AU":"Australia","BO":"Bolivia","BR":"Brasil","CA":"Canada","CL":"Chile","CN":"中国","CO":"Colombia","CR":"Costa Rica","CU":"Cuba","CZ":"Česká","DE":"Deutschland","DK":"Danmark","DO":"Rep. Dominicana","EC":"Ecuador","ES":"España","FI":"Suomessa","FR":"France","GR":"Ελλάδα","GT":"Guatemala","HU":"Magyarország","IE":"Ireland","IN":"India","IT":"Italia","JP":"日本","MX":"México","NI":"Nicaragua","NL":"Nederland","NO":"Norge","PA":"Panamá","PE":"Perú","PL":"Polska","PR":"Puerto Rico","PT":"Portugal","PY":"Paraguay","RO":"România","RU":"Россия","SE":"Sverige","SV":"El Salvador","TR":"Türkiye","UA":"Україна","UK":"United Kingdom","US":"USA","UY":"Uruguay","VE":"Venezuela"};
//populates country labels
var labels = [], size = 0;
for (var key in countryList){
labels.push(key);
size++;
}
var _data = function(){
var arr = [];
for (var n=0; n<size; n++){
arr.push(1);
}
return arr;
};
var dataset = [
{
label: "depreciation",
data: _data(),
backgroundColor: 'navy'
}, {
label: "insurance",
data: _data(),
backgroundColor: 'blue'
}, {
label: "credit",
data: _data(),
backgroundColor: 'aqua'
}, {
label: "inspection",
data: _data(),
backgroundColor: 'teal'
}, {
label: "road taxes",
data: _data(),
backgroundColor: 'olive'
}, {
label: "maintenance",
data: _data(),
backgroundColor: 'green'
}, {
label: "repairs",
data: _data(),
backgroundColor: 'lime'
}, {
label: "fuel",
data: _data(),
backgroundColor: 'maroon'
}, {
label: "parking",
data: _data(),
backgroundColor: 'yellow'
}, {
label: "tolls",
data: _data(),
backgroundColor: 'orange'
}, {
label: "fines",
data: _data(),
backgroundColor: 'red'
}, {
label: "washing",
data: _data(),
backgroundColor: 'purple'
}, {
label: "maintenance",
data: _data(),
backgroundColor: 'green'
}
];
var options = {
maintainAspectRatio: false,
legend: {
position: 'bottom', // place legend on the right side of chart
display: false, //do not display
labels : {
fontSize: 9,
fontColor: 'black'
}
},
scales: {
xAxes: [{
stacked: true, // this should be set to make the bars stacked
beginAtZero: true
}],
yAxes: [{
stacked: true, // this also..
beginAtZero: true
}]
},
animation: {
duration : 1000,
easing : 'linear'
}
};
var content = {
type: 'bar',
data: {
labels: labels,
datasets: dataset
},
options: options
};
//I made tests with timestamps and here it takes the biggest part of the time
new Chart(overallStatsChart, content);
.chart {
position: relative;
margin: auto;
}
#overallStatsChartDiv{
min-height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<div class="chart" id="overallStatsChartDiv">
<canvas id="overallStatsChart"></canvas>
</div>

ChartJS makes unwanted horizontal line on Safari

I'm currently working with ChartJS.
It works fine on Firefox and Chrome.
On Safari there is horizontal lines which appear. (here there is one good on orange and two others unwanted )
I have a lot of datapoint (2 lines of 1600 data point). I don't know if it could be a cause.
My code is here.
In some other part, I update time uni and time min.
_displayChart: function(label1, label2){
var timeFormat = 'DD/MM/YYYY HH:mm';
var ctx = document.getElementById(this.heading).getContext('2d');
const data = {
// Labels should be Date objects
//labels:this._stats[1],
datasets: [{
fill: false,
label: label1,
data: this._stats[2],
borderColor: '#fe8b36',
pointRadius: 0,
backgroundColor: [
'#fe8b36'
]
},{
label: label2,
fill: false,
data: this._stats[3],
borderWidth: 1,
pointRadius: 0,
borderColor: 'rgba(99, 100, 200, 1)',
backgroundColor: [
'rgba(99, 100, 200, 0.2)'
]
}]
}
const options = {
type: 'line',
data: data,
options: {
responsive: false,
fill: false,
responsive: true,
maintainAspectRatio:!this._isMobile(),
max: this.max,
hover: {
// Overrides the global setting
mode: 'index'
},
annotation: {
drawTime: 'beforeDatasetsDraw',
events: ['click'],
annotations: []
},
legend: {
labels: {
filter: function(legendItem, chartData) {
if(legendItem.datasetIndex == 2 || legendItem.datasetIndex == 3 ){
return false;
}
return true;
}
}
},
tooltips: {
mode:'index',
intersect : false,
callbacks: {
title: function(tooltipItems, data) {
return tooltipItems[0].xLabel.format(timeFormat);
},
label: function(tooltipItems, data) {
return tooltipItems.yLabel+'%';
}
}
},
scales: {
xAxes: [{
type: 'time',
display: true,
time:{
unit:'day',
min:moment(Date.now()-this.monthTs),
max:this._stats[1][this._stats[1].length]
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
},
display: true
}]
}
}
}
this._chart = new Chart(ctx, options);
},
When I'm applying this, I have no problem:
this._chart.options.scales.xAxes[0].time.unit = 'month';
this._chart.options.scales.xAxes[0].time.stepSize = 1;
this._chart.options.scales.xAxes[0].time.min = this._stats[1][0];
this._chart.options.scales.xAxes[0].time.max = this._stats[1][this._stats[1].length-1];
Thanks

Can not read property 'Concat' of Undefined

I am attempting to use the charts.js plug-in and do a combo chart, but I want the line to be on top of the bar. This is the syntax that I am using, and both my arrays linedata & bardata are populated but whenever I run this syntax I get an error of
Uncaught TypeError: Cannot read property 'concat' of undefined
at n (Chart.min.js:11)
at t.update (Chart.min.js:11)
at t.construct (Chart.min.js:11)
at new t (Chart.min.js:12)
at trends:507
This is the syntax I utulize - where is the error?
var ctx = document.getElementById('canvas').getContext('2d');
var chart = new Chart(ctx, {
data: {
labels: labelsarr,
datasets: [{
type: 'line',
fill: false,
label: 'Line Example',
backgroundColor: 'rgba(255,0,0,1)',
borderColor: 'rgba(255,0,0,1)',
data: linedata
}, {
type: 'bar',
label: 'Bar Example',
backgroundColor: 'rgba(0, 129, 214, 0.8)',
data: bardata
}]
},
options: {
tooltips: {
callbacks: {
label: function (t, d) {
var xLabel = d.datasets[t.datasetIndex].label;
var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
return xLabel + ': ' + yLabel;
}
}
},
legend: {
display: false,
position: 'top',
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback: function (value, index, values) {
if (parseInt(value) >= 1000) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}]
}
},
plugins: [{
beforeDraw: function(chart) {
var labels = chart.data.labels;
}
}]
});
Edit
This is how the arrays are being populated - values passed from php
var ldata = <?php echo $ldata; ?>;
var values = [];
for (var i = 0; i < ldata.length; i++) {
values.push(ldata[i]);
}
var bdata = <?php echo $bdata; ?>;
var values1 = [];
for (var i = 0; i < bdata.length; i++) {
values1.push(bdata[i]);
}
You would have to set the chart type in the main chart option, not inside the dataset (the second one) :
var chart = new Chart(ctx, {
type: 'bar',
data: {
...
Here is the working version of your code :
var labelsarr = ['A', 'B', 'C'];
var linedata = [2, 5, 3];
var bardata = [4, 2, 6];
var ctx = document.getElementById('canvas').getContext('2d');
var chart = new Chart(ctx, {
type: 'bar', //<-- set here
data: {
labels: labelsarr,
datasets: [{
type: 'line',
fill: false,
label: 'Line Example',
backgroundColor: 'rgba(255,0,0,1)',
borderColor: 'rgba(255,0,0,1)',
data: linedata
}, {
label: 'Bar Example',
backgroundColor: 'rgba(0, 129, 214, 0.8)',
data: bardata
}]
},
options: {
tooltips: {
callbacks: {
label: function(t, d) {
var xLabel = d.datasets[t.datasetIndex].label;
var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
return xLabel + ': ' + yLabel;
}
}
},
legend: {
display: false,
position: 'top',
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
if (parseInt(value) >= 1000) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}]
}
},
plugins: [{
beforeDraw: function(chart) {
var labels = chart.data.labels;
}
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>

chartjs: How to remove specific label

I have a Bar Chart with these data and options:
var data = {
labels: periodnames,
datasets: [
{
yAxisID: "bar-stacked",
data: rcash,
backgroundColor: "#FFCE56",
label:""
},
{
yAxisID:"bar-stacked",
data: pcash,
backgroundColor: "#FFCE56",
label: "cash"
}
]
};
var options = {
animation: {
animateScale: true
},
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [
{
display:false,
id: "line-axis",
},
{
id: "bar-stacked",
stacked: true,
}
]
}
}
finactivityGraphChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
The result chart is this:
My problem is that I don't want to show the first dataset's label. If I don't define it, it shows the yellow box with the value "undefine" next to it. I suppose that I must modify the Chart.js file. Any suggestions?
This could be achieved, using the filter function of legend­*'s* label.
see Legend Label Configuration
In short, add the following in your chart options ...
legend: {
labels: {
filter: function(label) {
if (label.text === 'cash') return true;
}
}
},
ᴅᴇᴍᴏ
var ctx = document.querySelector('#c').getContext('2d');
var data = {
labels: ['Jan', 'Feb', 'Mar'],
datasets: [{
yAxisID: "bar-stacked",
data: [1, 2, 3],
backgroundColor: "#FFCE56",
label: "gold"
}, {
yAxisID: "bar-stacked",
data: [-1, -2, -3],
backgroundColor: "#FFCE56",
label: "cash"
}]
};
var options = {
legend: {
labels: {
filter: function(label) {
if (label.text === 'cash') return true; //only show when the label is cash
}
}
},
animation: {
animateScale: true
},
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
display: false,
id: "line-axis",
}, {
id: "bar-stacked",
stacked: true,
}]
}
}
finactivityGraphChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
<canvas id="c"></canvas>

Categories