chore: 添加 label formatter 约束 (#82)

* chore: 添加 label formatter 约束

* chore: 添加 area stroke 反模式
This commit is contained in:
Joel Alan
2026-05-29 15:02:20 +08:00
committed by GitHub
parent d476f4420b
commit 3a5c070497
2 changed files with 73 additions and 1 deletions
+36
View File
@@ -242,6 +242,23 @@ chart.options({ label: { text: 'value' } });
// ✅ Correct: labels (plural)
chart.options({ labels: [{ text: 'value' }] });
// ❌ Wrong: labels formatter 把第一个参数当 datum 对象
// formatter 的第一个参数是 text 已映射的值(如 85不是 datum
// d.value 在数字 85 上为 undefined结果为 "undefined%"
chart.options({
labels: [{ text: 'value', formatter: (d) => d.value + '%' }],
});
// ✅ Correct: 用 text 函数直接访问 datum 并格式化(推荐)
chart.options({
labels: [{ text: (d) => d.value + '%' }],
});
// ✅ Correct: 或用 formatter 的正确用法val 是已映射的数值)
chart.options({
labels: [{ text: 'value', formatter: (val) => val + '%' }],
});
// ❌ Wrong: hex 色值放在数据中,被 Ordinal scale 当作类别 key
// 渲染颜色是 G2 默认调色板,图例显示无意义的 '#1e3a5f' 等字符串
const barData = [
@@ -285,6 +302,25 @@ chart.options({
},
});
// ❌ Wrong: area 图上使用 stroke + lineWidth 会包裹整个填充区域
// 底部和两侧也会被描边,正确做法是 view + children 叠加 area + line
chart.options({
type: 'area',
data,
encode: { x: 'date', y: 'value' },
style: { fill: '#FF5924', fillOpacity: 0.4, stroke: '#FF5924', lineWidth: 2 },
});
// ✅ Correct: view + area(填充) + line(顶部边缘线)
chart.options({
type: 'view',
data,
children: [
{ type: 'area', encode: { x: 'date', y: 'value' }, style: { fill: '#FF5924', fillOpacity: 0.4 } },
{ type: 'line', encode: { x: 'date', y: 'value' }, style: { stroke: '#FF5924', lineWidth: 2 } },
],
});
// ❌ Wrong: unnecessary scale type specification
chart.options({ scale: { x: { type: 'linear' }, y: { type: 'linear' } } });
@@ -143,7 +143,43 @@ chart.options({
## 常见错误与修正
### 错误:多系列面积图不加 stackY 导致互相遮挡
### 错误 1在 area mark 上使用 stroke + lineWidth 描边
```javascript
// ❌ 错误stroke + lineWidth 会包裹整个填充区域(底部、两侧都描边),
// 而不是仅顶部边缘线
chart.options({
type: 'area',
data,
encode: { x: 'date', y: 'value' },
style: {
fill: '#FF5924',
fillOpacity: 0.4,
stroke: '#FF5924', // ❌ 描边包裹整个区域
lineWidth: 2, // ❌
},
});
// ✅ 正确:用 view + children 叠加 area填充+ line顶部边缘线
chart.options({
type: 'view',
data,
children: [
{
type: 'area',
encode: { x: 'date', y: 'value' },
style: { fill: '#FF5924', fillOpacity: 0.4 },
},
{
type: 'line',
encode: { x: 'date', y: 'value' },
style: { stroke: '#FF5924', lineWidth: 2 },
},
],
});
```
### 错误 2多系列面积图不加 stackY 导致互相遮挡
```javascript
// ❌ 问题:多系列面积相互覆盖,后面的系列遮挡前面的
chart.options({