Reputation: 665
I'm working on Angular version 11.0.4
, I'm using ng2-charts version 2.4.2
.
I have to render basic line charts, with some custom features.
One of the features consists of color some grid lines based on external API values.
Here's an example: for the yValue 2 I want to have the red color.
Since I haven't found a good solution for this problem, I'm trying this: inside the LineChart Options, there's the yAxes object inside scales. There's a series of callbacks ( here's the documentation https://www.chartjs.org/docs/next/axes/#callbacks ) which gives me the values of the ticks after being rendered. Based on those values I update the color values of the grid lines.
The problem is that every single callbacks that the interface provides give a series of values that are not the ones the chart renders.
This is what I have written:
scales: {
...this.lineChartOptions.scales,
yAxes: [{
ticks: {
beginAtZero: true
}
afterTickToLabelConversion: (scale) => {
console.log(scale);
return scale;
}
}],
This is what the console.log prints:
And this is what the chart renders:
As you can see the console.log prints 10 values from 18 to 0. The chart renders the tick values from 19 to 17.
HTML code:
<canvas id="chartContainer" baseChart width="400" height="400" [datasets]="lineChartData" [labels]="lineChartLabels"
[options]="lineChartOptions" [colors]="lineChartColors" [legend]="lineChartLegend" [chartType]="lineChartType"
[plugins]="lineChartPlugins">
Upvotes: 1
Views: 466
Reputation: 31411
With the code you provided the ticks array contain the correct ticks if I try to print them normally: https://jsfiddle.net/Leelenaleee/bfc3evz1/6/.
If you want the number 2 to be red and the rest be black your best option is to update to the latest version of chart.js which means you need to use the beta of ng2-charts, then you can make use of the scriptable options.
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
}]
},
options: {
scales: {
y: {
ticks: {
color: ({
tick
}) => (tick.value === 12 ? 'red' : Chart.defaults.color)
}
}
}
}
}
var 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.5.1/chart.js"></script>
</body>
Upvotes: 1