How to use excess vertical space in stacked bar chart? - javascript

I am trying to create a stacked bar chart (with chart.js 3.7+) which uses the entire canvas:
new Chart(..., {
type: 'bar',
data: {
labels: ['a','b','c','d','e'],
datasets: [{
backgroundColor: '#ff00ff',
data: [20,40,60,40,20],
},{
backgroundColor: '#00ff00',
data: [100,200,300,200,100],
}]
},
options: {
maintainAspectRatio: false,
responsive: true,
plugins: {
legend: { display: false },
},
scales: {
x: {
display: false,
stacked: true
},
y: {
display: true,
stacked: true
}
}
}
});
When I use a normal bar chart the graph is stretched to use up all the vertical space:
But when I stack the bars the combined longest bar doesn't use up all the vertical space:
How can I get the stacked bar chart to stretch to use all available vertical space?
See example here.

You could sum your arrays, find the max value in the resulting array and set the options.scales.y.max property with this value :
let data1 = [20,40,60,40,20];
let data2 = [100,200,300,200,100];
let sum = data1.map(function (num, idx) {
return num + data2[idx];
});
let max = Math.max(...sum);
var options =
{
maintainAspectRatio: false,
responsive: true,
plugins: {
legend: { display: false },
},
scales: {
x: {
display: false,
stacked: true
},
y: {
display: true,
stacked: true,
max: max
}
}
};
var mychart = new Chart(document.getElementById('mycanvas2').getContext('2d'), {
type: 'bar',
data: {
labels: ['a','b','c','d','e'],
datasets: [{
backgroundColor: '#ff00ff',
data: data1
},{
backgroundColor: '#00ff00',
data: data2
}]
},
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<div style="width:400px; height: 200px">
<canvas id="mycanvas2"></canvas>
</div>

According to this issue with chart.js you can configure the y-axis bounds to fit the data:
options: {
scales: {
x: {
display: false,
stacked: true
},
y: {
display: true,
stacked: true,
bounds: 'data' <----------
}
}
}

Related

How to remove all gridlines, border and show only ticks on a chartjs horizontal bar chart

Following on from the answer in this post
I have the following chart which can also be found here
const d0 = new Date("2023-02-15T00:00:00.721Z").getTime()
const d1 = new Date("2023-02-15T01:00:00.721Z").getTime()
const d2 = new Date("2023-02-15T02:30:00.721Z").getTime()
const d3 = new Date("2023-02-15T03:20:00.721Z").getTime()
const d4 = new Date("2023-02-15T05:05:00.721Z").getTime()
let values = [d0, d1, d2, d3, d4];
let data = {
labels: [''],
datasets: [{
label: 'up',
axis: 'y',
data: [d1],
backgroundColor: 'red',
},{
label: 'down',
axis: 'y',
data: [d2],
backgroundColor: 'yellow',
},{
label: 'out',
axis: 'y',
data: [d3],
backgroundColor: 'green',
},{
label: 'up',
axis: 'y',
data: [d4],
backgroundColor: 'red',
}
]
};
const config = {
data,
type: 'bar',
options:{
elements: {
bar: {
borderWidth: 0
}
},
ticks: {
display: true
},
interaction: {
mode: 'dataset'
},
tooltip: {
mode: 'dataset'
},
hover: {
mode: 'dataset'
},
onClick: function (e) {
// debugger;
var activePointLabel =
this.getElementsAtEventForMode(e, 'dataset', { intersect: true }, false)
alert(activePointLabel[0].datasetIndex);
}
,
plugins: {
legend: {
display: false,
},
title: {
display: false,
},
},
indexAxis: 'y',
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
grid: {
display: true
},
min: d0,
ticks: {
callback: function(value, index, ticks) {
return moment(value).format('HH:mm');
}
},
// afterBuildTicks: axis => axis.ticks = values.map(v => ({ value: v }))
},
y: {
grid: {
display: false
},
stacked: true
},
}
}};
new Chart(document.getElementById("chart"), config);
This produces this...
]1
I would like to get rid of all the grids lines , except the ticks, but if I set the gird displays false the tick also disappear, and it also leave a border around the chart, etg something like
Is there a way to do this?
Just add border: {display: false}, to the scales configuration. (here is the link to the documentation)
...
scales: {
x: {
border: {
display: false,
},
...
},
...
}
...
Update added full running example:
const d0 = moment.duration('07:00:00').asMinutes();
const d1 = moment.duration('09:00:00').asMinutes();
const d2 = moment.duration('10:45:00').asMinutes();
const d3 = moment.duration('17:35:00').asMinutes();
const d4 = moment.duration('19:00:00').asMinutes();
let values = [d0, d1, d2, d3, d4];
let data = {
labels: [''],
datasets: [{
label: 'up',
axis: 'y',
data: [d1],
backgroundColor: 'red',
},{
label: 'down',
axis: 'y',
data: [d2],
backgroundColor: 'yellow',
},{
label: 'out',
axis: 'y',
data: [d3],
backgroundColor: 'green',
},{
label: 'up',
axis: 'y',
data: [d4],
backgroundColor: 'red',
}
]
};
const config = {
data,
type: 'bar',
options:{
plugins: {
tooltip: {
mode: 'dataset',
callbacks: {
label: function(item){
return moment().startOf('day').add({ minute: item.raw}).format('HH:mm');
}
}
},
legend: {
display: false,
},
title: {
display: false,
},
},
indexAxis: 'y',
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
min: d0,
border: { display: false },
ticks: {
callback: function(value, index, ticks) {
return moment().startOf('day').add({ minute: value}).format('HH:mm');
}
},
afterBuildTicks: axis => axis.ticks = values.map(v => ({ value: v }))
},
y: {
stacked: true,
grid: { display: false },
},
}
}};
new Chart(document.getElementById("chart"), config);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>
<script src="//cdn.jsdelivr.net/npm/moment#^2"></script>
<script src="//cdn.jsdelivr.net/npm/chartjs-adapter-moment#^1"></script>
<div class="chart" style="height:84px; width:350px;">
<canvas id="chart" ></canvas>
</div>
use tickColor (see below config) for v 3.8.2
scales: {
x: {
...
grid: {
display: true,
drawTicks: true, //show ticks
borderColor: "transparent", //horizontal line color above ticks (x-axis)
color: "transparent", //grid lines color
tickColor: "#868e96" //ticks color (little line above points)
},
},
...
}

Chart JS Tooltip Currency Problem - Stacked Bar Chart

I use ChatJS and i want to add an € Symbol after every number in the Tooltip.
On my most charts it works perfectly but the Stacked Bar Chart makes me problems.
Here is an example Code like mine (Just a basic Example)
var barChart = new Chart(ctx_barChart, {
type: 'bar',
data: {
labels: ["Fruits"],
datasets: [{
label: [
["Apple"]
],
data: [12],
backgroundColor: 'blue',
barThickness: 80,
},
{
label: ["Banana"],
data: [15],
backgroundColor: 'red',
barThickness: 80,
},
]
},
options: {
maintainAspectRatio: false,
indexAxis: 'y',
responsive: true,
scales: {
x: {
stacked: true,
display: false,
},
y: {
stacked: true,
display: false,
mirror: true,
}
},
plugins: {
tooltip: {
callbacks: {
label: function(context) {
let label = context.dataset.label || '';
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
label += new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'EUR'
}).format(context.parsed.y);
}
return label;
}
}
},
legend: {
display: false
},
title: {
display: false,
},
},
},
});
The tooltips both show 0,00$, but not my Values 12 and 15. Anyone have an suggestiont?
You should use context.parsed.x instead of context.parsed.y since it's a horizontal bar chart.
Please take a look at your amended code and see how it works.
new Chart('barChart', {
type: 'bar',
data: {
labels: ["Fruits"],
datasets: [{
label: "Apple",
data: [12],
backgroundColor: 'blue',
barThickness: 80,
},
{
label: "Banana",
data: [15],
backgroundColor: 'red',
barThickness: 80,
},
]
},
options: {
maintainAspectRatio: false,
indexAxis: 'y',
responsive: true,
scales: {
x: {
stacked: true,
display: false,
},
y: {
stacked: true,
display: false,
mirror: true,
}
},
plugins: {
tooltip: {
callbacks: {
label: ctx => ctx.dataset.label + ': ' + new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(ctx.parsed.x)
}
},
legend: {
display: false
},
title: {
display: false,
},
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="barChart" height="100"></canvas>

Chart js: bar width

I want to display data in chart js (version 3.7.1) with horizontal bar chart. Data are loading from backend. My problem is with widht of bar. When I have only a few records, bars are very thick.1 When I have a lot of records (for example 1000) bars are very narrow and are missing label.2 How can you see in images.
I would like have still the same widht for bars and if is a lot of records enable scroll.
There is my code:
createConfig(config: ChartConfigDto): ChartConfiguration {
return {
type: 'bar',
data: {
labels: config.labels,
datasets:
config.datasets.map((dataset, index) => ({
label: dataset.label,
backgroundColor: `${CHART_COLORS[index]}`,
borderColor: `${CHART_COLORS[index]}`,
data: dataset.data,
barThickness: 'flex',
}))
},
options: {
indexAxis: 'y',
plugins: {
title: {
display: true,
text: 'Sites',
},
legend: {
position: 'top',
},
},
responsive: true,
scales: {
x: {
stacked: true,
position: 'top',
},
y: {
stacked: true,
grid: {
display: false,
},
}
},
},
}
}
<div class="modal-body">
<canvas appChart [config]="config"></canvas>
</div>
Thank you for help
There are two properties you can use to achieve.
barThickness
maxBarThickness
You can use maxBarThickness property in the dataset.
Here I'm attaching Stackblitz demo

Legends in Chart.js, shows only one label

Just a warning: I am new to chart.js!
I have a couple of horizontal bar charts and it works fine except one issue that I cannot shake off. I have 5 labels in y-axis but the legend on top of the graph only shows one small rectangle in the color of the first (topmost) bar and even that does not display the label itself, followed by list of labels. I thought it would display each label next to small bar same color as in chart.
Unfortunately, this is an intranet app and I cannot provide a link but here is what I have (data is passed to this function from an ajax call):
function drawRespChart(chartLabels, chartData) {
var ctx = $("#rtChart");
console.log("Labels Array: " + chartLabels);
console.log("Data Array: " + chartData);
if (chartRespTime)
chartRespTime.destroy();
var chart = {
labels: chartLabels,
datasets: [
{
label: chartLabels,
backgroundColor: ["#c45850", "#e8c3b9", "#3cba9f", "#8e5ea2", "#3e95cd"],
data: chartData
}
]
};
chartRespTime = new Chart(ctx, {
type: 'horizontalBar',
data: chart,
datalabels: {
anchor: 'end',
align: 'start',
},
options: {
title: {
display: true,
text: 'IDC Database Response Time (mili-seconds)'
},
legend: {
display: true,
labels: {
fontColor: 'rgb(255, 99, 132)'
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Count'
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Response Time (ms)'
}
}]
},
plugins: {
datalabels: {
color: 'white',
display: function (context) {
return context.dataset.data[context.dataIndex] > 15;
},
font: {
weight: 'bold'
},
formatter: Math.round
}
},
maintainAspectRatio: true,
responsive: true,
showInlineValues: true,
centeredInllineValues: true,
tooltipCaretSize: 0
}
});
}
This is what I see in console window:
Labels Array: 0-350,350-700,700-1000,1000-1500
Data Array: 5065,32,27,3
What I see as legend is one rectangle, same color as first bar, followed by list of labels.
It seems that charts.js labels only works when you split the datasets.
Leaving an example.
https://jsfiddle.net/code4mk/1j62ey38/
datasets: [ {
label: 'Result',
fill:false,
data: aDatasets1,
backgroundColor: '#E91E63',
},
{
label: 'Result2',
fill:false,
data: aDatasets2,
backgroundColor: '#E91E93',
}];

Start bar-chart at 0 using ChartJS

I have a bar chart which use ChartJS that shows data. Based on the bar chart, I have the data: 15, 2, 0, 11.
I can see all of these data in the bar, except 0. Is there a possibility to start the bar chart on 0, so I can also see the data for the fourth column in the bar chart?
options: {
legend: { display: false },
scales: {
yAxes: [{
display: false,
}],
xAxes: [{
display: true,
}],
},
title: {
display: false,
}
}
After hours of working, finally i found a soulution. There is no chartjs configuration to do it and you have to draw it your self. Let do it in onComplete function
var ctx = document.getElementById("myChart").getContext('2d');
var datasets = [15, 2, 0, 11];
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["1", "2", "3", "4"],
datasets: [{
label: 'value',
backgroundColor: '#F00',
data: datasets
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
animation: {
onComplete: function() {
var dataSet = myChart.getDatasetMeta(0);
dataSet.data.forEach(elm => {
if (datasets[elm._index] == 0) {
ctx.fillStyle = '#F00';
ctx.fillRect(elm._model.x - elm._view.width / 2, elm._model.y - 1, elm._view.width, 2);
}
})
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas class="canvasChart" id="myChart"></canvas>
You can try beginAtZero:true config option.
options: {
legend: { display: false },
scales: {
yAxes: [{
display: false,
ticks: {
beginAtZero:true
}
}],
xAxes: [{
display: true,
}],
},
title: {
display: false,
}
}
Because your Y-axis values starts from 0 to something. So, if your value is 0 in X-Axis than it would be null and won't show you bar of 0. So, if you want 0 to appear in chart your starting point should be less than the 0.
I believe you said you were using chartsjs. This question already has an answer here.
Try this, chart will start with zero.
options: {
responsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});

Categories