Bar graph not taking 100% - chart.js

I have a problem when generating a bar chart :
I don't understand why 50%+50% doesn't smoke 100% of the seat? Config seems to be good ? Did i miss something?
Here the code :
new Chart(draw, {
type: 'bar',
data: {
labels: [currentYear],
datasets: [
{
label: 'Legend 1',
data: [50],
backgroundColor: '#fdfd96', // yellow
},
{
label: 'Legend 2',
data: [50],
backgroundColor: '#77b5fe', // blue
},
],
},
options: {
scales: {
x: {
stacked: true,
},
y: {
stacked: true,
},
},
animation: {
onComplete: function () {
saveChartAsImage(
this.toBase64Image(),
currentYear,
companyId,
'actif',
manualMode,
);
},
},
},
});

Your code and configuration looks correct and works ( demo seen below ) but if you want to be on the save side yo can add the properties max:100 to the y axis, this could fix the hight issue.
Here the demo:
const data = {
labels: [2022],
datasets: [{
label: 'Legend 1',
data: [50],
backgroundColor: '#fdfd96', // yellow
},
{
label: 'Legend 2',
data: [50],
backgroundColor: '#77b5fe', // blue
},],
};
const config = {
type: 'bar',
data: data,
options: {
maintainAspectRatio: false,
animation: {
onComplete: function () {
let img = document.createElement('img')
let url = this.toBase64Image()
img.src = url
document.querySelector('#imagePreview').append(img);
}
},
scales: {
x: {
stacked: true,
},
y: {
stacked: true,
max:100
},
}}
};
var cart = 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>
<b> preview Image </b>
<div id="imagePreview"></div>
Update screenshot of result:
Update:
After testing the assumtion must be, that the save function is defective or there is some sort of race condition with a different chart. Since createing a image onComplete creates a correct images, in the updated demo.
I'm assuming the wrong visuals have to to with the animation, not being finished when the image is created, if this is so, one could workaround this fact (or just to test the theory), with using a timeout for creating the image, something like this
onComplete: function () {
setTimeout( () => {
saveChartAsImage(
this.toBase64Image(),
currentYear,
companyId,
'actif',
manualMode,
);
}, 1000); // <-- One Second should be enough for the animation to end
}

Related

chartjs backdropcolor of y scale ticks not showing

I played around with the stacked bar chart at
https://www.chartjs.org/docs/latest/samples/bar/stacked.html
Its currently looking like that:
config:
const config = {
type: 'bar',
data: data,
options: {
plugins: {
title: {
display: true,
text: 'Chart.js Bar Chart - Stacked'
},
},
responsive: true,
indexAxis: 'y',
scales: {
x: {
stacked: true,
title: {
display: true,
text: 'x-axis description',
},
},
y: {
ticks: {
mirror: true,
z: 1,
backdropColor: 'rgba(255, 0, 255, 0.75)'
},
stacked: true,
title: {
display: true,
text: 'y-axis description',
},
}
}
}
};
setup:
const labels = ['Short Label', 'vryshrtlbl', 'a litle bit more longer label', 'pretty veeeeeeeeeeeeeeeeeeeeeerylong label', 'ultra extreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeemly long label']
const data = {
labels: labels,
datasets: [
{
label: 'Losers',
data: [-1,-2,-3,-44,-5],
backgroundColor: 'rgba(255, 0, 0, 0.5)',
},
{
label: 'Winners',
data: [6,12,23,55,5],
backgroundColor: 'rgba(255, 0, 0, 1)',
}
]
};
The thing is, that I may have such long labels. Since I dont want to waste space for them which makes the actual chart smaller I decided to bring the tick labels into the chart area.
But I would make them a bit better visible:
may move then to the right/center a bit
I already tried padding but this also shrinks the chart area, thats a no-go
bring a backgroundcolor like a grey box behind the tick labels such that there is no switch from white background to red bar behind the text
I was sure to achive that with backdropColor bit this option does not do anything.
from documentation I am sure I placed the setting correctly but I dont see any background behind the tick labels
Any Ideas why this does not work?
btw: I tried to provide a jsfiddle but when I place my code there it is ignoring the 'indexAxis' property and the 'stacked: true' as well. The first one I can workaround by using "type: 'horizontalBar'". But not the stacked one. Is this any kind of old writing this 'horizontalBar'? On chartjs page itself they are using 'bar' only.
If this may also could be answered then I may can prepare a fiddle in the future.
But one can reproduce my problem by going to
https://www.chartjs.org/docs/latest/samples/bar/stacked.html
and replace the contents with mine above.
Thanks.
Well for your first part of your question I have no solution. (it might be possible if you write a plugin or so, but no out-of-the-box solution, that I know of)
For part two "the grey box", check the demo below.
In short you will have to set the parameter showLabelBackdrop to true.
Here a demo, how I would do this:
let labels = ['Short Label', 'vryshrtlbl', 'a litle bit more longer label', 'pretty veeeeeeeeeeeeeeeeeeeeeerylong label', 'ultra extreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeemly long label']
const data = {
labels: labels,
datasets: [
{
label: 'Losers',
data: [-1,-2,-3,-44,-5],
backgroundColor: 'rgba(255, 0, 0, 0.5)',
},
{
label: 'Winners',
data: [6,12,23,55,5],
backgroundColor: 'rgba(255, 0, 0, 1)',
}
]
};
const config = {
type: 'bar',
data: data,
options: {
plugins: {
title: {
display: true,
text: 'Chart.js Bar Chart - Stacked'
},
},
responsive: true,
indexAxis: 'y',
scales: {
x: {
stacked: true,
title: {
display: true,
text: 'x-axis description',
},
},
y: {
ticks: {
mirror: true,
backdropColor: '#cdcdcd',
backdropPadding: 0, // <- Adjust the box padding
showLabelBackdrop: true,
z: 1,
},
stacked: true,
title: {
display: true,
text: 'y-axis description',
},
}
}
}
};
new Chart(
document.getElementById('chart'),
config
);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>
<div class="chart" style="height:300px; width:500px;">
<canvas id="chart" ></canvas>
</div>

ChartJS 'Line chartjs' does not show output in NodeRED?

My requirement is to output 2 y-axis chart with real-time data readings in NodeRED. I have installed ChartJS package in NodeRED and now according to the documentation of the package there should be PATH, Title, X-Axis, Y-Axis, Payload. But I couldn't find the Payload tab anywhere in the Line Chartjs node?
Ref : https://www.npmjs.com/package/node-red-contrib-chartjs
So I assumed that I have to add the code which belonged to Payload inside a function node before the Line Chartjs node.
What I have tried : (my function node)
var left = {payload : msg.payload.readResults[0].v };
var right = {payload : msg.payload.readResults[1].v };
//return [[left,right]];
const labels = [1,2,3,4,5,6,7,8,9,10];
const data = {
labels: labels,
datasets: [
{
label: 'Dataset 1',
data: left,
borderColor: '#ff0000',
backgroundColor: '#ff0000',
yAxisID: 'leftCamber',
},
{
label: 'Dataset 2',
data: right,
borderColor: '#0000ff',
backgroundColor: '#0000ff',
yAxisID: 'rightCamber',
}
]
};
const config = {
type: 'line',
data: data,
options: {
responsive: true,
interaction: {
mode: 'index',
intersect: false,
},
stacked: false,
plugins: {
title: {
display: true,
text: 'Chart.js Line Chart - Multi Axis'
}
},
scales: {
leftCamber: {
type: 'linear',
display: true,
position: 'left',
},
rightCamber: {
type: 'linear',
display: true,
position: 'right',
// grid line settings
grid: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
},
}
},
};
const actions = [
{
name: 'CamberGraph',
handler(chart) {
chart.data.datasets.forEach(dataset => {
dataset.data = chart.data.labels.length
});
chart.update();
}
},
];
Here I have tried to get the 2 HTTP outputs I've named as left and right as my datasets(2 y-axis) vs hardcoded x-axis(1 through 10) which will be Footage later on.
PS : I have returned the left and right using return statement and it's outputting the values as I expected.
Currently I do not get any output in my debug window as well as in my ChartJS Line Chart when I inject the node. Using what I've tried so far can anybody show where I've done wrong or add/remove anything to make the graph work?
Thank you!

ChartJs - Doughnut Chart - how to remove labels if percentage is less than a limit

I am using doughnut from chart.js for visualization in my application.
I need to remove the label if the percentage is bellow a static value like ,20%
This is what i used to generate the labels
var myChartOptions= {
responsive: true,
animation: {
animateScale: true,
animateRotate: true
},
plugins: {
labels: {
render: 'percentage',
fontColor: '#000000',
precision: 2,
}
}
};
I've been working at this for awhile now with no luck.
It looks like chartjs-plugin-labels is being used, in which case passing a custom function to the render option will do the trick, as per the documentation:
const data = [1, 2, 7],
myChartOptions = {
responsive: true,
animation: {
animateScale: true,
animateRotate: true
},
plugins: {
labels: {
render: args => {
if (args.percentage < 20) {
return '';
}
return args.percentage + '%';
},
fontColor: '#000000',
precision: 2,
}
}
};
new Chart(document.getElementById('myChart'), {
type: 'doughnut',
data: {
datasets: [{
label: 'series 1',
data: data,
backgroundColor: ['pink', 'lightgreen', 'lightblue'],
}]
},
options: myChartOptions
});
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<canvas id="myChart"></canvas>

How can I change the color of certain lines in chartjs / vue-chartjs?

I notice that a default bar chart always has a darker zero line. I also notice the horizontal line at -1.0 is also darker. I want those colors to be the same as the grid. How do I do that?
A bare-bones example is shown here:
https://jsfiddle.net/Lnv3cmz0/1/
Vue.component('chart', {
template:`
<canvas></canvas>
`,
props:['type'],
mounted(){
this._chart = new Chart(this.$el, {
type:this.type,
data:[],
})
},
})
//App setup
new Vue({
el:'#vue',
})
Update:
The zeroLine option no longer seems to be available. I am using the latest/greatest Chart (v4.2.0) and no longer have this issue. Below is a sample of what I'm doing
const ctx = document.getElementById('chart') as HTMLCanvasElement;
chart.value = new Chart(ctx, {
type: 'bar',
data: {
datasets: [],
},
options: {
onClick: (evt) => handleOnClick(evt),
interaction: {
mode: 'nearest',
},
plugins: {
legend: {
labels: {
generateLabels(chart) { // other code here }}
}
},
title: {
display: true,
text: 'My Super cool Chart',
},
},
scales: {
x: {
grid: {
color: () => myBackgroundColor,
},
beginAtZero: false,
ticks: {
callback: (value) => doSomethingOnCallaback(value),
// fontColor: myBackgroundColor,
},
type: 'linear',
},
y: {
grid: {
color: () => myBackgroundColor,
},
max: myStart,
min: myEnd,
beginAtZero: false,
ticks: {
callback: (value) => `Tick ${value}`,
stepSize: 15.0,
},
},
},
},
});
The answer is zeroLineColor in the GridLines
https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration

On hover bar is overlapped by label chartjs

I'm trying to generate a bar graph but after generating when i hover on bar first graph the hover works and tooltip is also coming correctly but when i hover on second or third bar the bar color becomes black
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<canvas id="barChart" style="margin-top:10px"></canvas>
var ctxBarChart = document.getElementById('barChart').getContext('2d');
var chart = new Chart(ctxBarChart, {
// The type of chart we want to create
type: 'bar',
// The data for our dataset
data: {
labels: ['bar 1', 'bar 2', 'bar 3'],
datasets: [{
label: 'bar graph label',
backgroundColor: ['#ff7f27', 'DodgerBlue', 'Green'],
borderColor: ['#ff7f27', 'DodgerBlue', 'Green'],
data: [24.6154, 28.4, 28.4]
}]
},
// Configuration options go here
options: {
legend: {
display: false
},
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
return tooltipItem.yLabel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,') + '%';
}
}
},
scales: {
xAxes: [{
gridLines: {
display: false
}
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
// max: 100,
min: 0,
// stepSize:20
}
}]
}
}
});
but the result i'm getting is like this please see following images for bar 1 and bar 2
This seems to be caused by case-sensitivity of colour names.
Change your colours to all lowercase like so:
backgroundColor: ['#ff7f27', 'dodgerblue', 'green'],
borderColor: ['#ff7f27', 'dodgerblue', 'green'],
The CSS3 specification explicitly states the names are case-insensitive so this looks like a bug in Chart.js