Reputation: 361
I am creating different chat for analysis one of them is bar chart in which i need to fill color according to the value if value is less than or equal to 20 color is red,if 20 to 60 color should be yellow and if it is more than 60 than it should be green.
code is below given
JS:-
var ctx6 = document.querySelector('#resultsChart6').getContext('2d');
var options6 = {
type: 'bar',
data: {
labels: ['Label1','Label2','Label3','Label4','Label5'],
responsive: false,
datasets: [{
label: "Your Score in %",
data: [((section1Total / (section1Question * 5)) * 100),((section2Total / (section2Question * 5)) * 100),((section3Total / (section3Question * 5)) * 100),((section4Total / (section4Question * 5)) * 100),((section5Total / (section5Question * 5)) * 100)],
backgroundColor: '#2ecc71'
}
]
},
options: {
responsive: true,
legend: {
position: 'top' // place legend on the right side of chart
},
scales: {
xAxes: [{
stacked: true // this should be set to make the bars stacked
}],
yAxes: [{
stacked: true // this also..
}]
}
}
}
new Chart(ctx6, options6);
Upvotes: 1
Views: 1474
Reputation: 31439
You can use scriptable options for this:
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 20, 23, 50, 60, 65],
backgroundColor: (ctx) => {
if (ctx.raw <= 20) {
return 'red';
}
if (ctx.raw <= 60) {
return 'yellow';
}
return 'green';
}
}]
},
options: {}
}
const 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.2/chart.js"></script>
</body>
Upvotes: 2