I am working with a horizontal bar chart using Chart.js, and I need to display two different colors for each bar based on their values. Specifically, if a bar's value exceeds 150, I want the portion of the bar above 150 to be red, while the portion below or equal to 150 should remain grey.
Here’s a visual representation of what I’m trying to achieve: Current Implementation:
I am fetching data from a MySQL database and rendering it in the chart. Here is my current script:
<script>
let myChart = document.getElementById('myChart').getContext('2d');
// Global options
Chart.defaults.global.defaultFontFamily = 'Lato';
Chart.defaults.global.defaultFontSize = 18;
Chart.defaults.global.defaultFontColor = '#666';
let massPopChart = new Chart(myChart, {
type: 'horizontalBar',
data: {
labels: [
<?php
for ($i = 0; $i < count($phoneNumberArr); $i++) {
echo "'$phoneNumberArr[$i]'".($i < count($phoneNumberArr) - 1 ? ',' : '');
}
?>
],
datasets: [{
label: 'Belföldi perc',
data: [
<?php
for ($i = 0; $i < count($valueArr); $i++) {
echo "'$valueArr[$i]'".($i < count($valueArr) - 1 ? ',' : '');
}
?>
],
backgroundColor: 'rgba(0,0,0,0.6)', // Default color
borderWidth: 1,
borderColor: '#777',
hoverBorderWidth: 3,
hoverBorderColor: '#FFF'
}],
},
options: {
title: {
display: false,
text: 'Összesítő',
fontSize: 25
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#000'
}
},
layout: {
padding: {
left: 50,
right: 0,
bottom: 0,
top: 0
}
},
}
});
</script>
Questions:
Additional Information:
I am using Chart.js version.
The chart currently displays a single color for the bars, and I want to implement the two-color logic based on the value threshold.
The way I solved it before is by using a stacked bar in chart js. You should go through your values and every time a value is higher then 150 you set 150 in dataset1 and the amount that is above 150 you put in dataset2. and If your amount is lower than 150 you put in the amount in dataset1 and put 0 in dataset2. Here you can see an example of how I did it.
var config = {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May"],
datasets: [{
type: 'bar',
label: 'Dataset 1',
backgroundColor: "blue",
data: [150, 150, 60, 50, 40],
}, {
type: 'bar',
label: 'Dataset 2',
backgroundColor: "red",
data: [45,25,0,0,0]
}]
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.0/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>