问题标题
VChart如何给离散数据配置渐变色?
问题描述
我希望给不同数值的图元设置插值渐变的颜色,如下图的案例,每个扇区的颜色具有差值关系。
解决方案
可以通过自定义颜色映射来实现。
首先,您需要通过scales来声明映射关系,其中id表示映射的唯一索引,field表示数据映射字段,color表示映射的目标颜色, 您可以在这里配置具有插值的颜色色板。
color: {
id: 'color',
type: 'linear',
range: ['#1664FF', '#B2CFFF', '#1AC6FF', '#94EFFF'],
domain: [
{
dataId: 'id0',
fields: ['value']
}
]
},
其次,您需要在扇区图元的样式中关联映射。其中scale表示关联的映射id, field表示数据映射字段/
fill: {
scale: 'color',
field: 'value'
}
代码示例
const pieData = [
{ type: 'oxygen', value: '46.60' },
{ type: 'silicon', value: '27.72' },
{ type: 'aluminum', value: '8.13' },
{ type: 'iron', value: '5' },
{ type: 'calcium', value: '3.63' },
{ type: 'sodium', value: '2.83' },
{ type: 'potassium', value: '2.59' },
{ type: 'others', value: '3.5' }
];
const spec = {
type: 'pie',
data: [
{
id: 'id0',
values: pieData
}
],
outerRadius: 0.8,
innerRadius: 0.5,
padAngle: 0.6,
valueField: 'value',
categoryField: 'type',
color: {
id: 'color',
type: 'linear',
range: ['#1664FF', '#B2CFFF', '#1AC6FF', '#94EFFF'],
domain: [
{
dataId: 'id0',
fields: ['value']
}
]
},
pie: {
style: {
cornerRadius: 10,
fill: {
scale: 'color',
field: 'value'
}
}
},
legends: {
visible: true,
orient: 'left',
data: (data, scale) => {
return data.map(datum => {
const pickDatum = pieData.find(pieDatum => pieDatum.type === datum.label);
datum.shape.fill = scale?.scale?.(pickDatum?.value);
return datum;
});
}
},
label: {
visible: true
}
};
const vchart = new VChart(spec, { dom: CONTAINER_ID });
vchart.renderSync();
// Just for the convenience of console debugging, DO NOT COPY!
window['vchart'] = vchart;
结果展示
在线效果参考:www.visactor.io/vchart/demo…
相关文档
渐变饼图Demo: www.visactor.io/vchart/demo…
相关教程:www.visactor.io/vchart/guid…
github:github.com/VisActor/VC…