首页 > 解决方案 > 如何使用 Ngx-Charts customColor 功能

问题描述

您如何将 customColor 属性用作函数?我正在寻找建立一个散点图并将所有具有负值的点标记为红色,将所有具有正值的点标记为绿色。我认为 customColor 功能可以让我这样做,但我只看到 customColor 作为对象而不是函数的示例。谢谢!

标签: ngx-charts

解决方案


HTML 模板

<ngx-charts-bar-vertical
      [animations]="barAnimations"
      [customColors]="barCustomColors()"
      ...
</ngx-charts-bar-vertical>

零件

...
   barAnimations = false;
   barSingle = [
      {"name": "56","value": 654},
      {"name": "57","value": 123},
      ...
   ]

   constructor() {}

   ngOnInit() {}

   // your custom function
   // make sure return structure is array like
   // [
   //    {"name": "a","value": "#ff0000"},
   //    {"name": "b","value": "#ff0000"}
   // ]   
   barCustomColors() {
      let result: any[] = [];
      for (let i = 0; i < this.barSingle.length; i++) {
         if (this.barSingle[i].value < 200) {
            result.push({"name": this.barSingle[i].name,"value": "#0000ff"});
         }
      }
      return result;
   }
...

然后图表将在创建图表时调用该函数。

确保自定义函数返回数组并包含颜色的名称和值。它像是:

[
   {"name": "a","value": "#ff0000"},
   {"name": "b","value": "#ff0000"}
]

但是如果打开动画模式,它会调用该函数的次数过多,并出现以下问题。

requestAnimationFrame 处理程序花费了 ms

它会使你的图表绘制太慢。因此,如果您想使用函数来控制和自定义图表颜色。建议关闭动画模式。


推荐阅读