phantom phantom - 15 days ago 6
Javascript Question

Chart.js combine two pieces of data into one bar

I am using

charts.js
to display data. i have it set up and it is working.

However, I have read through all the documentation and cannot figure out how to solve what I want to achieve.

Currently, the
data
contains three numbers
[12, 19, 3]
. this is the number of actual goals scored. However, there is also a prediction as to the number of goals scored. This value is always going to be less based on the data I have. so the expected goals scored are
[8, 11, 1]
. these correspond with the first set.

Is there anyway to combine the two values in the same bar. So in the first bar, it would go to 8, as the expected number of goals, and then the top part of the bar would show the actual number of goals.

Here is my code below.

Hopefully my question makes sense

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow"],
datasets: [{
label: '# of Goals',
data: [12, 19, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: false,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});




var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow"],
datasets: [{
label: '# of Likes',
data: [12, 19, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: false,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.bundle.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>




Answer

Version 2 does support stacked bar charts.

https://jsfiddle.net/r71no58a/10/

   scales: {
        xAxes: [{
            stacked: true,
        }],
        yAxes: [{
            stacked: true,
            ticks: {
                beginAtZero: true
            }
        }]
   }
Comments