如何根据数据在ng2图表和chart.js中自定义颜色



我希望构建一个折线图,并将某个值以上的所有点标记为红色,将该值以下的所有点都标记为蓝色。我试着用ngx图表这样做,但没有成功。如何使用ng2图表?这可能吗?如有任何帮助,我们将不胜感激。

您可以将dataset上的选项pointBackgroundColor定义为每个点的颜色数组。为此,您可以使用Array.map(),如下所示:

pointBackgroundColor: this.data.map(v => v > 60 ? "red" : "blue"),

这基本上为大于60的值绘制红色点,否则绘制蓝色点。

请查看CodeSandbox并了解其工作原理。

HTML:

<canvas baseChart width="400" height="360"
[data]="chartData"
[options]="chartOptions"
[type]="chartType">
</canvas>

TS:


import { Component, ViewChild, OnInit } from '@angular/core';
import { ChartConfiguration, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
export class MyChartComponent implements OnInit {
@ViewChild(BaseChartDirective) chart?: BaseChartDirective;
constructor() {}
ngOnInit(): void {}
public chartData: ChartConfiguration['data'] = {
datasets: [
{
data: [10, 32, 21, 48],
label: 'My Data',
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
pointBackgroundColor: 'rgba(54, 162, 235, 1)',
pointBorderColor: 'rgba(255, 255, 255, 1)',
pointHoverBackgroundColor: 'rgba(255, 255, 255, 1)',
pointHoverBorderColor: 'rgba(54, 162, 235, 1)',
fill: 'origin',
},
],
labels: ['A', 'B', 'C', 'D']
};
public chartOptions: ChartConfiguration['options'] = {
elements: {
line: {
tension: 0.5
}
},
scales: {
x: {},
y: {
position: 'left',
beginAtZero: true,
grid: {
color: 'rgba(100, 100, 100, 0.3)',
},
ticks: {
color: '#666'
}
},
},
maintainAspectRatio: false,
plugins: {
legend: { display: true },
}
};
public chartType: ChartType = 'line';
}

您只需要将这些样例颜色更改为自己的颜色即可。

最新更新