G2Plot 条形图颜色渐变设置教程 - 使用 scale 和 formatter
在 G2Plot 中,可以使用 scale 来设置条形图的颜色渐变。具体操作步骤如下:
- 导入渐变色插件
import { registerShape } from '@antv/g2';
import { getTheme } from '@antv/g2/lib/theme';
const { colors10 } = getTheme();
registerShape('interval', 'gradient', {
draw(cfg, container) {
const points = cfg.points;
const width = cfg.size;
const height = Math.abs(points[0].y - points[2].y);
const min = Math.min(points[0].y, points[2].y);
const max = Math.max(points[0].y, points[2].y);
const gradientCfg = {
// 颜色映射数组,值为 0~1 范围内的数值
color: [colors10[0], colors10[9]],
// 渐变起点,值为 0~1 范围内的数值
start: { x: 0, y: 0 },
// 渐变终点,值为 0~1 范围内的数值
end: { x: 0, y: 1 },
};
const defs = container.get('defs') || container.addGroup().get('defs');
// 定义线性渐变
const linearGradient = defs.addGradient({
id: 'interval-gradient',
x1: 0,
y1: 0,
x2: 0,
y2: 1,
});
// 添加渐变色
linearGradient.addColorStop(gradientCfg.start.x, gradientCfg.color[0]);
linearGradient.addColorStop(gradientCfg.end.x, gradientCfg.color[1]);
return container.addShape('rect', {
attrs: {
x: points[0].x - width / 2,
y: min,
width,
height,
fill: `url(#${linearGradient.attr('id')})`,
},
});
},
});
- 设置渐变色
const data = [
{ name: 'A', value: 10 },
{ name: 'B', value: 20 },
{ name: 'C', value: 30 },
{ name: 'D', value: 40 },
];
const scale = {
value: {
max: 50,
min: 0,
alias: '数值',
// 设置渐变色
formatter: (v) => ({
value: v,
style: { color: `rgb(255, ${255 - (v / 50) * 255}, 0)` },
}),
},
};
const chart = new Bar('container', {
data,
xField: 'name',
yField: 'value',
scale,
// 使用渐变色
shape: 'gradient',
});
chart.render();
以上是 G2Plot 条形图颜色渐变设置的示例代码。需要注意的是,渐变色的设置需要在 scale 中进行,并且需要使用 formatter 函数来返回带有样式的数值。另外,需要在 chart 的配置项中设置 shape 属性为 'gradient',表示使用渐变色。
原文地址: https://www.cveoy.top/t/topic/lU8B 著作权归作者所有。请勿转载和采集!