chat,js stacked bar chart (make one dataset into stacked) - chart.js

Trying to put one dataset into stacked on bar chart .. is it possible ?? please refer my fiddle link fiddle here,
Just want to make test 3 data into stacked one.
my datasets are passed like this `
var dataSet = '';
var datasets = [];
for (i in label) {
dataSet = {
label: label[i],
data: dataY[i]
};
datasets.push(dataSet);
}
var barData = {
labels: dataX,
datasets: datasets
};
`

You need to enable the stacked option on both the x and y axes:
var stackedBar = new Chart(document.getElementById('chart'), {
type: 'bar',
data: {
labels: [1,2,3],
datasets: [{
label: 'series1',
backgroundColor: 'red',
data: [1,2,1],
stack: 1
},{
label: 'series2',
backgroundColor: 'lightblue',
data: [1,2,2],
stack: 2
},{
label: 'series3',
backgroundColor: 'lightgreen',
data: [2,1,2],
stack: 2
}]
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chart"></canvas>

As far as I searched google It seems it is not possible to put stacked grouped graph using chart.js and solution is to use D3.js

Related

Bar graph not taking 100%

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
}

cartesian coordinate system with chart.js

I'm trying to create a cartesian coordinate system (i.e. for coordinate geometry) using chart.js. The documentation actually states "cartesian axes" but I'm not seeing any evidence that such a name is warranted. My chart is as follows:
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'Scatter Dataset',
data: [{x:-3,y:5},{x:-2,y:0},{x:-1,y:-3},{x:0,y:-4},{x:1,y:-3},
{x:2,y:0},{x:3,y:5}]
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
ticks: {
stepSize: 1
}
}],yAxes: [{
type: 'linear',
ticks: {
stepSize: 1
}
}]
}
}
});
</script>
Problem right now is that the axes aren't passing through the origin (0,0). They are set off to the side just like any other ordinary chart. Does anyone know how to move the axes?
I tried setting the position of the axes but the only options are 'top', 'bottom', 'left' and 'right'. There is no 'middle', 'center', 'origin', etc. I also tried setting a label offset but this doesn't move in the right direction (x labels move in x direction, y labels move in y direction - I need the opposite) and this is only moving the labels anyway.
You can use the Plugin Core API that offers a range of hooks that may be used for performing custom code. In the beforeDraw for example, you can compute and set the ticks.padding of both axes in order to move the ticks to the desired position.
beforeDraw: chart => {
var xAxis = chart.scales['x-axis-1'];
var yAxis = chart.scales['y-axis-1'];
const scales = chart.chart.config.options.scales;
scales.xAxes[0].ticks.padding = yAxis.top - yAxis.getPixelForValue(0) + 6;
scales.yAxes[0].ticks.padding = xAxis.getPixelForValue(0) - xAxis.right + 6;
}
Please take a look at your amended code and see how it works.
new Chart('myChart', {
type: 'scatter',
plugins:[{
beforeDraw: chart => {
var xAxis = chart.scales['x-axis-1'];
var yAxis = chart.scales['y-axis-1'];
const scales = chart.chart.config.options.scales;
scales.xAxes[0].ticks.padding = yAxis.top - yAxis.getPixelForValue(0) + 6;
scales.yAxes[0].ticks.padding = xAxis.getPixelForValue(0) - xAxis.right + 6;
}
}],
data: {
datasets: [{
label: 'Scatter Dataset',
data: [{x:-3,y:5},{x:-2,y:0},{x:-1,y:-3},{x:0,y:-4},{x:1,y:-3},{x:2,y:0},{x:3,y:5}],
borderColor: 'red'
}]
},
options: {
scales: {
xAxes: [{
ticks: {
min: -6,
max: 6,
stepSize: 1,
callback: v => v == 0 ? '' : v
},
gridLines: {
drawTicks: false
}
}],
yAxes: [{
ticks: {
min: -6,
max: 6,
stepSize: 1,
callback: v => v == 0 ? '' : v
},
gridLines: {
drawTicks: false
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

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

Chartjs bar chart trying to get labels from datasets

I am trying to implement chartJS bar chart and use the legend to filter bars.
I want to set the labels list to be empty because this allows me to remove bars clearly.
I am looking for a way to set the ticks with labels on X axis, since it is empty from text now.
JSfiddle:
https://jsfiddle.net/m1eorjwv/1/
var options = {
type: 'bar',
data: {
labels: [],
datasets: [
{
label: 'red',
data: [12],
borderWidth: 1
},
{
label: 'blue',
data: [7],
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
reverse: false,
beginAtZero: true
}
}]
}
}
}
Thanks a lot, Alon
I managed to do this, here is the ansert:
enter code here
code
https://jsfiddle.net/ehacujny

How to show different product name for every bar in chart js

I am using chart js for showing top 3 sold products in last week.
I want to show product name in tooltip for every bar which has obviously different products.
Here is my code :
function productChart() {
var data = {
labels: productHistoryDates,
datasets: [{
label: 'Product 1',
data: productHistoryProducts1,
backgroundColor: "#26B99A"
},
{
label: 'Product 2',
data: productHistoryProducts2,
backgroundColor: "#03586A",
},
{
label: 'Product 3',
data: productHistoryProducts3,
backgroundColor: "#03226A",
}]
};
var ctx = document.getElementById("productChart").getContext("2d");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
tooltips: {
enabled: true,
mode: 'single',
},
scales: {
yAxes: [{
gridLines: {
display: true
}
}],
xAxes: [{
gridLines: {
display: true
},
barPercentage: 0.8
}]
}
}
});
}
I am getting output like this.
But instead of product 1 label I want product name for that particular bar how can I achieve that ?
I solved it.
by passing an array to the label in data. And rest of the code is as below.
function productChart() {
var data = {
labels: productHistoryDates,
datasets: [{
label: productHistoryProducts1.name,
data: productHistoryProducts1.quantity,
backgroundColor: "#26B99A"
},
{
label: productHistoryProducts2.name,
data: productHistoryProducts2.quantity,
backgroundColor: "#03586A",
},
{
label: productHistoryProducts3.name,
data: productHistoryProducts3.quantity,
backgroundColor: "#03226A",
}]
};
var ctx = document.getElementById("productChart").getContext("2d");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function (tooltipItems, data) {
var tooltip = data.datasets[tooltipItems.datasetIndex].label[tooltipItems.index];
return tooltip;
}
}
},
scales: {
yAxes: [{
gridLines: {
display: true
}
}],
xAxes: [{
gridLines: {
display: true
},
ticks: { mirror: true },
barPercentage: 0.8
}]
}
}
});
}