Start bar-chart at 0 using ChartJS - javascript

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
}
}]
}
}
});

Related

How to use excess vertical space in stacked bar chart?

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' <----------
}
}
}

Failed to execute 'createLinearGradient' on 'CanvasRenderingContext2D': The provided double value is non-finite

I'm trying to create a linear gradient under plugins for my chartJs chart.Unfortunately I get an error called :
Failed to execute 'createLinearGradient' on 'CanvasRenderingContext2D': The provided double value is non-finite.
I'm trying to add my linearGradient inside plugins because I want that gradient to be aligned on each scale.
Here what I tried below
barChart = new Chart(elem, {
plugins: [
{
id: "responsiveGradient",
afterLayout: function(chart, options) {
var scales = chart.scales;
var color = chart.ctx.createLinearGradient(
scales["x-axis-0"].left,
scales["y-axis-0"].bottom,
scales["x-axis-0"].right,
scales["y-axis-0"].top
);
// add gradients stops
color.addColorStop(0, "black");
color.addColorStop(0.25, "red");
color.addColorStop(0.5, "orange");
color.addColorStop(0.75, "yellow");
color.addColorStop(1, "green");
// changes the background color option
chart.data.datasets[0].backgroundColor = color;
}
}
],
type: 'horizontalBar',
data: datasets,
options: {
maintainAspectRatio: false,
tooltips: { enabled: false },
title: {
display: false,
},
responsive: true,
legend: {
display: false,
position: "top"
},
scales: {
xAxes: [{
ticks: {
beginAtZero: false,
min:0.5,
max:0.8,
maxTicksLimit: 6,
},
scaleLabel: {
display: false
},
barThickness: 5,
gridLines: {
display: false,
zeroLineColor: "transparent",
}
}],
yAxes: [{
barThickness: 5,
ticks: {
maxTicksLimit: 6,
padding: 15,
},
gridLines: {
drawTicks: false,
display: false
}
}]
}
},
});
The problem is in the last line of your plugins.afterLayout function. There is no object such as chart.data, use chart.config.data instead.
// chart.data.datasets[0].backgroundColor = color; // replace this line
chart.config.data.datasets[0].backgroundColor = color;
Please have a look at your amended code below (I had to make an assumptions about your data).
const datasets = {
labels: ['A', 'B', 'C'],
datasets: [{
label: 'data',
data: [0.6, 0.7, 0.8],
barThickness: 5
}]
};
new Chart("myChart", {
plugins: [{
id: "responsiveGradient",
afterLayout: (chart, options) => {
var scales = chart.scales;
var color = chart.chart.ctx.createLinearGradient(
scales["x-axis-0"].left,
scales["y-axis-0"].bottom,
scales["x-axis-0"].right,
scales["y-axis-0"].top
);
// add gradients stops
color.addColorStop(0, "black");
color.addColorStop(0.25, "red");
color.addColorStop(0.5, "orange");
color.addColorStop(0.75, "yellow");
color.addColorStop(1, "green");
// changes the background color option
chart.config.data.datasets[0].backgroundColor = color;
}
}],
type: 'horizontalBar',
data: datasets,
options: {
maintainAspectRatio: false,
tooltips: {
enabled: false
},
title: {
display: false,
},
responsive: true,
legend: {
display: false,
position: "top"
},
scales: {
xAxes: [{
ticks: {
beginAtZero: false,
min: 0.5,
max: 0.8,
maxTicksLimit: 6,
},
scaleLabel: {
display: false
},
gridLines: {
display: false,
zeroLineColor: "transparent",
}
}],
yAxes: [{
ticks: {
maxTicksLimit: 6,
padding: 15,
},
gridLines: {
drawTicks: false,
display: false
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>

How can I remove extra whitespace from the bottom of a line chart in chart.js?

As you can see below with the canvas element highlighted, there is considerable whitespace below the x axis label. If I resize the canvas, the whitespace stays proportional to the height of it. Are there any settings that control this whitespace? I've ruled out padding and do not see any settings for margins.
Thanks!
Here is the JavaScript that renders the chart:
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
options: {
legend: {
display: false
},
elements: {
point: {
radius: 0
}
},
scales: {
xAxes: [{
gridLines: {
display: false,
drawBorder: true
},
ticks: {
autoSkip: true,
maxTicksLimit: 1
}
}],
yAxes: [{
gridLines: {
display: true,
drawBorder: false
},
ticks: {
callback: function(value, index, values) {
return '$' + addCommas(value);
}
}
}]
},
layout: {
padding: 5
}
},
type: 'line',
data: {
labels: labels,
datasets: [
{
data: values,
fill: false,
borderColor: "blue"
}
]
}
});
And the complete jsfiddle: https://jsfiddle.net/rsn288fh/2/
I know you said you ruled out padding, but this is the only option I can see working:
options: {
layout: {
padding: {
bottom: -20
}
}
}
Obviously you can play with the -20 to what works for you.
Here is the reference for padding for chartjs, if you wanted to see more
EDIT:
I've updated your jsfiddle, with a colored div below the chart. As you resize it seems to stay at the same spot below the chart.
Changing the tickMarkLength to 0 results in no padding on the left or bottom of the chart (or wherever your axis happens to be).
https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration
tickMarkLength
Length in pixels that the grid lines will draw into the axis area.
const options = {
scales: {
xAxes: [
{
ticks: {
display: false,
},
gridLines: {
display: false,
tickMarkLength: 0,
},
},
],
yAxes: [
{
ticks: {
display: false,
},
gridLines: {
display: false,
tickMarkLength: 0,
},
},
],
},
};

Chartjs last label not shown

[UPDATE] The question seems to be solved (see comments). I will update the answer as soon as i am sure about it
I am trying to achieve a weather chart using chartjs library.
The chart will always have the weather date of the first day of the month and in addition to that one value in between (makes 24 values).
I want all "first day of the month" labels to be shown (with the corresponding gridline), the other data point in between should not be shown (or at least with no gridline).
The Problem now, somehow the last (12th) label is not gonna be shown and I have no idea why. The result looks like that:
My javascript code is that
var ctx = document.getElementById('canvas').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [
"01","","02","","03","","04", "","05","","06","","07","","08","","09","","10","","11", "","12",""
],
datasets: [{
label: 'Temperature [°C]',
data: [
1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6
],
borderColor: "rgb(0, 182, 206)",
pointRadius: 1,
backgroundColor: "rgba(0, 182, 206,0.4)"
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
legend:{
display:false // Suppress interactive legend
},
scales: {
xAxes: [{
scaleLabel: {
display: false,
labelString: 'Month'
} ,
afterTickToLabelConversion: function(data){
var xLabels = data.ticks;
xLabels.forEach(function (labels, i) {
if (xLabels[i].length == 0){
xLabels[i] = '';
}
});
},
ticks: {
//maxRotation: 0,
//minRotation: 0,
autoSkip: true,
maxTicksLimit: 12
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Temperature [°C]'
},
ticks: {
beginAtZero: true
}
}]
}
}
});
Do you have some ideas?

Change color of X and Y axis values in Chart.js

I'm using v2.*. However, I can't seem to set the default color for a line chart. I'm mainly looking to set the color of the x/y chart values. I figured the below might do it - but it does nothing to the chart at all.
Chart.defaults.global.defaultColor = 'orange',
Update
Here's a jsfiddle with live chart. In short, I'm looking to change the color of the labels i.e. Feb 7, 2016, etc etc.
https://jsfiddle.net/o534w6jj/
Okay, so I figured it out. It's the ticks property I'm looking for...see code below.
See updated jsfiddle: https://jsfiddle.net/o534w6jj/1/
var ctx = $("#weekly-clicks-chart");
var weeklyClicksChart = new Chart(ctx, {
type: 'line',
data: data,
scaleFontColor: 'red',
options: {
scaleFontColor: 'red',
responsive: true,
tooltips: {
mode: 'single',
},
scales: {
xAxes: [{
gridLines: {
display: false,
},
ticks: {
fontColor: "#CCC", // this here
},
}],
yAxes: [{
display: false,
gridLines: {
display: false,
},
}],
}
}
});
for anyone using Chartjs v3+ you can try this.
options: {
...
scales: {
y: {
ticks: {
color: 'red'
}
}
,
}
}

Categories