以下是一个使用Vega-Lite制作饼图,并调整标签位置的代码示例:
// 导入需要的库
import { compile } from 'vega-lite';
import { View } from 'vega';
// 定义数据
const data = {
"values": [
{"category": "A", "value": 10},
{"category": "B", "value": 20},
{"category": "C", "value": 30},
{"category": "D", "value": 40},
{"category": "E", "value": 50}
]
};
// 定义Vega-Lite规范
const spec = {
"$schema": "https://vega.github.io/schema/vega-lite/v4.json",
"width": 400,
"height": 400,
"data": data,
"mark": {"type": "arc", "innerRadius": 0},
"encoding": {
"theta": {"field": "value", "type": "quantitative"},
"color": {"field": "category", "type": "nominal"},
"tooltip": {"field": "value", "type": "quantitative"}
},
"config": {
"view": {"stroke": "transparent"},
"arc": {"stroke": "white"},
"axis": {"grid": false},
"legend": {"orient": "none"},
"label": {
"fontSize": 14,
"fontWeight": "bold",
"radiusOffset": 0.6,
"thetaOffset": -90
}
}
};
// 编译Vega-Lite规范为Vega规范
const vegaSpec = compile(spec).spec;
// 创建Vega视图
const view = new View(parse(vegaSpec))
.renderer('svg') // 指定渲染器为SVG
.initialize('#vis') // 将图表渲染到id为vis的元素中
.hover() // 启用鼠标悬停交互
.run(); // 运行视图
在上面的代码中,我们使用Vega-Lite规范定义了一个饼图,并使用"label"配置选项调整了标签的位置。具体来说,我们使用"label"配置选项中的"radiusOffset"属性将标签移动到扇形的内部,使用"thetaOffset"属性调整标签的角度。这样可以确保标签显示在饼图的中心,同时保持标签与饼图的对齐。
请注意,上述代码中的#vis
是一个HTML元素的id,用于指定图表将被渲染的位置。您可以根据自己的需要将其更改为其他值。
上一篇:饼图VBA数据标签格式化