0👍
✅
You can make use of backgroundColor
property of dataset and pass an array to it. The array can be built based on data so you can add your own logic to return the color you want.
Something like this:
const ctx = document.getElementById('myChart');
const request = [
{x: 'Station1',y: 5},
{x: 'Station2',y: 2},
{x: 'Station3',y: 1},
{x: 'Station4',y: 8},
{x: 'Station5',y: 7},
{x: 'Station6',y: -2},
{x: 'Station7',y: 10},
{x: 'Station8',y: 0}
]
const labels = request.map(function(e) { return e.x; });
const colors = request.map(function(e) {
if (e.y <= 0) {
return '#ff6384'
} else if (e.y >= 0 && e.y <= 4) {
return '#36a2eb';
} else {
return '#cc65fe';
}
});
const fuelChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
data: request,
label: 'Day to posts',
backgroundColor: colors
}]
},
options: {
responsive: true,
scales: {
x: {
type: 'category',
labels: labels,
}
}
}
})
0👍
This can be done by using Arrays.map()
as follows:
backgroundColor: request.map(o => o.y < 0 ? 'red' : 'blue')
Please take a look at your amended and runnable code below and see how it works.
const ctx = document.getElementById('chart');
const request = [
{x: 'Station1',y: 5},
{x: 'Station2',y: 2},
{x: 'Station3',y: 1},
{x: 'Station4',y: 8},
{x: 'Station5',y: 7},
{x: 'Station6',y: -2},
{x: 'Station7',y: 10},
{x: 'Station8',y: 0}
]
const labels = request.map(function(e) {return e.x;});
const fuelChart = new Chart(ctx,{
type:'scatter',
data: {
datasets: [{
data: request,
label:'Day to posts',
backgroundColor: request.map(o => o.y < 0 ? 'red' : 'blue')
}]
},
options: {
responsive: true,
scales:{
x:{
type:'category',
labels:labels
}
}
}
})
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
<canvas id="chart" height="80"></canvas>
Source:stackexchange.com