效果展示
需求:
- 内层饼图为一级分类,外层饼图为二级分类。
- 内外层一级分类和多属的二级分类颜色一样,且悬浮二级分类,一级分类同样有高亮效果。
- 一级分类和二级分类悬浮有释义说明(解释这个分类的含义)
- 由于二级分类只展示其中一部分,所以一级分类和二级分类所占角度不一样。
关键代码展示
** 定义option**
const colors = ["#fc8251", "#5470c6", "#91cd77", "#ef6567", "#f9c956"];
const twoPieOption = ref({
title: {
text: "",
textStyle: {
color: "#000",
fontSize: 24,
},
left: "100px",
},
tooltip: {
trigger: "item",
// formatter: "{a} <br/>{b}: {c} 项 ({d}%)",
formatter: function (params) {
return `${params.seriesName}:${params.data.name}<br>释义:${params.data.meaning}`;
},
},
legend: {
orient: "vertical",
x: "left",
data: ["分类A", "分类B", "分类C"],
},
series: [
{
name: "一级分类",
type: "pie",
selectedMode: "single",
radius: ["10%", "30%"],
label: {
position: "inner",
textStyle: {
color: "#000",
fontSize: 20,
},
},
labelLine: {
show: false,
},
itemStyle: {
color: function (params) {
return colors[params.dataIndex % colors.length];
},
},
data: [],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: "rgba(0, 0, 0, 0.5)",
},
},
},
{
name: "二级分类",
type: "pie",
radius: ["30.5%", "55%"],
label: {
formatter: "{a|{a}}{abg|}\n{hr|}\n {b|{b}:}{c} 项 {per|{d}%} ",
backgroundColor: "#eee",
borderColor: "#aaa",
borderWidth: 1,
borderRadius: 4,
// textStyle: {
// color: "#000",
// fontSize: 14,
// },
rich: {
a: {
color: "#999",
lineHeight: 22,
align: "center",
},
hr: {
borderColor: "#aaa",
width: "100%",
borderWidth: 0.5,
height: 0,
},
b: {
fontSize: 16,
lineHeight: 33,
},
per: {
color: "#eee",
backgroundColor: "#334455",
padding: [2, 4],
borderRadius: 2,
},
},
},
data: [],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: "rgba(0, 0, 0, 0.5)",
},
},
itemStyle: {
color: function (params) {
return colors[params.dataIndex % colors.length];
},
},
},
],
});
填充数据
- 通过接口获取数据(简单举例)
特别注意饼图中data的数据结构
// 一级分类:
data: [{name: '一级名称', value:123}]
// 二级分类:
// 注意多一个parent字段
// 注意二级分类颜色,是通过一级分类的下标去取值的
data: [{
name: '二级名称',
value:12,
parent:‘一级名称’},
itemStyle: { color: colors[index]
}]
// 简单说明,取值赋值逻辑
const { data } = await getData()
const { series } = twoPieOption;
series[0].data = [];
data.forEach((item, index) => {
series[0].data.push({
name: item.ipc_main_small_type,
value: item.number,
meaning: item.meaning || "",
index,
});
item.ipc_main_big_group.forEach((p) => {
series[1].data.push({
name: p.ipc_main_big_group,
value: p.number,
parent: item.ipc_main_small_type,
meaning: p.meaning || "",
itemStyle: { color: colors[index] },
index,
});
});
});
Charts.setOption(option);
// 鼠标悬浮在二级分类上时触发一级分类高亮
Charts.on("mouseover", function (params) {
if (params.data.name) {
Charts.dispatchAction({
type: "highlight",
seriesIndex: 0,
dataIndex: params.data.index,
});
}
});
// 鼠标离开,取消之前的悬浮效果
Charts.on("mouseout", function (params) {
if (params.data.name) {
Charts.dispatchAction({
type: "downplay",
seriesIndex: 0,
dataIndex: params.data.index,
});
}
});