Chart.js Bar Chart change width (not duplicated to bar width questions!) - chart.js

How can I change the bar width? I mean, the width from the bar I could change, but not this:

The bar width is influenced through the options barPercentage and categoryPercentage, which both need to be defined on the dataset.
To find out about the relationship between barPercentage and categoryPercentage, see here.
In case you simply want to see the existing bars closer to each other, you need to change the height of the chart. This can be done directly on the canvas as follows:
<canvas id="canvas" height="40"></canvas>
Please have a look at the following code snippet.
new Chart(document.getElementById('canvas'), {
type: 'horizontalBar',
data: {
labels: ['A', 'B'],
datasets: [{
label: 'data',
data: [15, 8],
backgroundColor: 'rgba(0, 0, 255, 0.2)',
borderColor: 'rgb(0, 0, 255)',
borderWidth: 1
}]
},
options: {
responsive: true,
legend: {
display: false
},
title: {
display: false
},
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="canvas" height="40"></canvas>

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 Polar Area Chart - Data labels shown don't rotate with startAngle

I am setting the startAngle on my polar chart so the first category starts on the -180 degrees.
But I can't figure out why the data point labels don't correspondingly adjust and rotate. As a result, they show up incorrectly against the wrong data. As you can see in the image, Question 6 still appears where Question 1 should be. The tooltips on each section do appear correctly.
Note: When I use the datalabels plugin, it does show the label correctly. But I am not using it because it does not wrap the labels and also it cuts off the labels if they become too big. In addition I had responsiveness problems with it.
So please suggest a solution without that plugin if possible.
Thank you very much for helping me out.
const mydata = {
labels: [
'Question1',
'Question2',
'Question3',
'Question4',
'Question5',
'Question6'
],
datasets: [{
label: 'Data labels don't move',
data: [5, 8, 6, 6, 7, 8],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(75, 192, 192)',
'rgb(255, 205, 86)',
'rgb(201, 203, 207)',
'rgb(255, 99, 132)',
'rgb(201, 203, 207)'
]
}]
};
var myChart = new Chart('mychartId'),
{
type: "polarArea",
data: mydata,
options:
{
responsive: true,
cutoutPercentage: 20,
startAngle: -1 * Math.PI,
legend: {
display: false
},
layout: {
padding: 20
},
scale: {
ticks: {
max: 10,
beginAtZero: true,
min: 1,
stepSize: 1,
display: false
},
angleLines: {
display: false
},
pointLabels: {
display: true
}
}
}
}
sample image showing the problem
Update to V3, there they do turn with the chart if you adjust the startAngle
var options = {
type: 'polarArea',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [2, 9, 3, 5, 2, 3],
borderWidth: 1
}]
},
options: {
scales: {
r: {
startAngle: 180,
ticks: {
display: false
},
pointLabels: {
display: true
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
V3 has some breaking changes over V2, for all of them you can read the migration guide

charts js have a bar spanning negative/positive on y-axis

Is there a way in chartjs to have a bar span across the zero line? As an example,
lets say I have a bar with
data:[x:1, y:100]
How do I tell it to span the y-axis from -100 to 100 (instead of from 0 to 100)?
I have sort of a playground here where I can do either negative or positive per bar, but not both for one bar.
https://jsbin.com/dufonoceja/1/edit?js,output
This can be done since Chart.js v2.9.0, which now supports floating bars. Individual bars can now be specified with the syntax [min, max].
<html>
<head>
<title>Floating Bars</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div>
<canvas id="canvas" height="120"></canvas>
</div>
<script>
var chartData = {
labels: [1,2,3,4,5,6],
datasets: [{
type: 'bar',
label: 'Red Bar',
borderColor: 'black',
borderWidth: 1,
backgroundColor: 'rgba(128,0,0,0.2)',
data: [[0, 100], [-100, 100], [-30, 40], 0, 0, 0],
}, {
type: 'bar',
label: 'Green Bar',
backgroundColor: 'rgba(0,128,0,0.2)',
borderColor: 'black',
borderWidth: 1,
data: [0, 0, 0, 0, [-50, 70], 100],
}
]
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
scaleBeginAtZero: false,
responsive: true,
spanGaps: true,
tooltips: {
mode: 'index',
intersect: true
},
scales: {
xAxes: [{
gridLines: {
display: false
},
}],
yAxes: [{
type: 'linear',
ticks: {
beginAtZero: false,
min:-100,
max:100,
stepSize:30
}
}],
}
}
});
};
</script>
</body>
</html>

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

How do I invert an y-axis using chart.js (v2.0-dev)

I am creating line charts with 2 y-axes. one of those axes has two datasets but both run from the range of 0-100. The higher number being the better one. The second y-axis is usually lower in range (often in the single digits) and the best result is 1.
How can I invert the second y-axis so that 1 is at the top of the chart?
(I will try to find a solution myself, but at 5k+ lines in chart.js, it might take a while )
Thanks ^_^
Dev 2.0 of chart js supports an option to reverse the ticks when setting up the axis so your declaration of the second axis would become
{
type: "invertedLinear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "right",
id: "y-axis-2",
ticks: {
reverse: true
},
// grid line settings
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
}
}
Here it is in action https://jsfiddle.net/nwc8ys34/15/
Using v 2.7.0, and the following seems to work:
options: {
scales: {
yAxes: [{
ticks: {
reverse: true,
}
}]
}
}
In v3 the scale configs have been changed so the desired behaviour can be accomplished like so:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [40, 80, 100, 70, 60, 80],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange',
yAxisID: 'y2'
}
]
},
options: {
scales: {
y: {},
y2: {
position: 'right',
reverse: true
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
Chart.js 4:
datasets: [{
label: "Strength",
yAxisID: "y1",
data: mappedData.sigStrength
}, {
label: "Bars",
yAxisID: "y2",
data: mappedData.sigBars
}]
scales: {
y1: {
type: "linear",
display: true,
position: "left",
reverse: true
},
y2: {
type: "linear",
display: true,
position: "right",
ticks: {
stepSize: 1
}
}
},