简体   繁体   English

如何根据数据在 ng2-charts 和 chart.js 中自定义 colors?

[英]How to have custom colors in ng2-charts and chart.js according to data?

I'm looking to build a line graph and mark all points above a certain value as red, and all those below that value as blue.我正在寻找建立一个折线图并将高于某个值的所有点标记为红色,所有低于该值的点标记为蓝色。 I tried doing so with ngx-chart but that did not work.我尝试使用 ngx-chart 这样做,但没有奏效。 How do I do so with ng2-charts?我该如何使用 ng2-charts? Is that even possible?这甚至可能吗? Any help would be greatly appreciated.任何帮助将不胜感激。

You can define the option pointBackgroundColor on the dataset as an array of colors for each point.您可以将dataset上的选项pointBackgroundColor定义为每个点的 colors 数组。 To do so, you could use Array.map() as follows:为此,您可以使用Array.map()如下:

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

This basically draws red points for values above 60, blue points otherwise.这基本上为高于 60 的值绘制红点,否则为蓝点。

Please take a look at this CodeSandbox and see how it works.请看一下这个CodeSandbox ,看看它是如何工作的。

HTML: HTML:

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

TS: 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';
}

You only have to change these sample colors to your own ones.您只需将这些示例 colors 更改为您自己的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM