如何将customColor属性用作函数?我希望构建一个散点图,并将所有具有负值的点标记为红色,将所有具有正值的点标记为绿色。我认为customColor功能可以让我做到这一点,但我只看到过将customColor作为对象而不是函数的示例。谢谢!
发布于 2018-11-21 19:52:09
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处理程序用了毫秒
这会使你的图表绘制速度太慢。因此,如果您想使用function来控制和自定义图表颜色。建议关闭动画模式。
发布于 2020-09-13 06:08:40
您需要传递一个准备好的颜色数组,而不是一个函数
setCustomColors() {
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": "#ff0000"});
}
else{
result.push({"name": this.barSingle[i].name,"value": "#33cc33"});
}
}
return result;
}
customColors: any;并在组件创建时设置该值
constructor() {
this.customColors = this.setCustomColors();
}发布于 2020-10-08 01:38:24
在許聖泉的回答上进行扩展....
一种确保颜色仅在必要时计算的方法。您可以将图表包装在一个组件中,该组件在数据更改时调用自定义颜色的生成。通过这种方式,您可以在不影响性能的情况下获得动画以及自定义颜色功能。
因此,在包装器组件中,您会看到如下内容
...
multiVal: any = [];
@Input()
set multi(data: any) {
this.generateCustomColors();
this.multiVal = data;
}
get multi() {
return this.multiVal;
}
...
...
generateCustomColors() {
if (this.multi === undefined) {
return [];
}
// This is where you calculate your values.
// I left my conversion using a custom Color class for reference.
// Similar concept can be used for single series data
const values = {};
// for (const mult of this.multi) {
// for (const serie of mult.series) {
// if (values[serie.name] === undefined) {
// values[serie.name] = {
// name: serie.name,
// value: Color.hexFromString(serie.name),
// };
// }
// }
// }
this.customColors = Object.values(values);
}
...https://stackoverflow.com/questions/50765823
复制相似问题