【发布时间】:2022-08-03 17:37:10
【问题描述】:
我正在寻找建立一个折线图并将高于某个值的所有点标记为红色,所有低于该值的点标记为蓝色。我尝试使用 ngx-chart 这样做,但没有奏效。我该如何使用 ng2-charts?这甚至可能吗?任何帮助将不胜感激。
标签: angular chart.js ng2-charts ngx-charts
我正在寻找建立一个折线图并将高于某个值的所有点标记为红色,所有低于该值的点标记为蓝色。我尝试使用 ngx-chart 这样做,但没有奏效。我该如何使用 ng2-charts?这甚至可能吗?任何帮助将不胜感激。
标签: angular chart.js ng2-charts ngx-charts
您可以将dataset 上的选项pointBackgroundColor 定义为每个点的颜色数组。为此,您可以使用Array.map(),如下所示:
pointBackgroundColor: this.data.map(v => v > 60 ? "red" : "blue"),
这基本上为高于 60 的值绘制红点,否则为蓝点。
请看一下这个CodeSandbox,看看它是如何工作的。
【讨论】:
ngOnInit(){ console.log(this.chartData.pointBackgroundColor) } 中控制台记录 pointBackgroundColor[] 时,我收到以下错误:Property 'pointBackgroundColor' does not exist on type 'ChartDataset<keyof ChartTypeRegistry, (number | ScatterDataPoint | BubbleDataPoint)[]>[]'。为什么会这样?我该如何解决这个问题?
ChartDataset 可能与底层的 Chart.js 代码不同步。您可以改用以下内容:console.log(this.chartData[0]['pointBackgroundColor'])
console.log(this.chartData[0].pointBackgroundColor) 时,角度显示相同的错误。您对这种差异背后的原因有任何想法吗?两种语法的意思是一样的吧?所以在我看来,两者都应该工作?另外,如果我想对没有点的条形图和折线图做同样的事情,我应该将颜色数组绑定到的属性 pf ChartDataset 是什么?
pointBackgroundColor 没有在ChartDataset 上定义。在第二种情况下,编译器不检查属性是否真的存在,因此这些情况是不同的。对于bar 图表和line 无点图表,请尝试使用属性backgroundColor 和borderColor。
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: '#fff',
pointHoverBackgroundColor: '#fff',
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';
}
您只需将这些示例颜色更改为您自己的颜色。
【讨论】: