要在 legend 中显示名称、值和百分比,你需要自定义 legend 的 formatter 函数。ECharts 的 legend 支持使用 formatter
回调来自定义显示内容,并且可以通过 legend.pageIcons
等配置优化布局。
以下是修改后的代码,主要添加了 legend 的 formatter 函数,并优化了饼图的标签显示:
const list = res.data?.records || [];
console.log('原始数据:', list); // 调试用,查看原始数据结构
const data = list.map(item => {
console.log('当前处理项:', item); // 调试用,查看每个项的结构
// 统一使用 typeName 或 TypeName,根据你的数据结构来定
const typeName = item.typeName || item.TypeName; // 尝试两种可能的属性名
const obj = {
...item,
value: item.count,
name: typeName || '未知类型', // 确保 name 字段有值
};
// 根据 typeName 设置不同的颜色
if (typeName === '一搬') {
obj.itemStyle = {
color: '#165DFF' };
} else if (typeName === '较大') {
obj.itemStyle = {
color: '#FFFF00' };
} else if (typeName === '特大') {
obj.itemStyle = {
color: '#D9001B' };
} else if (typeName === '重大') {
obj.itemStyle = {
color: '#F59A23' };
}
return obj;
});
console.log('处理后的数据:', data); // 调试用,查看处理后的数据
// 计算总数值,用于百分比计算
const total = data.reduce((sum, item) => sum + (item.value || 0), 0);
const option = {
title: {
},
tooltip: {
trigger: 'item',
formatter: '{b}: {c} ({d}%)' // 显示名称、值和百分比
},
legend: {
orient: 'vertical',
right: 0,
bottom: 0,
show: true,
type: 'scroll', // 启用滚动,防止数据过多时溢出
pageButtonItemGap: 5,
pageButtonGap: 10,
pageIconColor: '#999',
pageIconInactiveColor: '#ccc',
pageIconSize: 12,
pageTextStyle: {
color: '#999'
},
// 自定义图例格式:名称 + 值 + 百分比
formatter: function(name) {
const item = data.find(item => item.name === name);
if (!item || item.value === undefined) return name;
const value = item.value;
const percent = total > 0 ? Math.round((value / total) * 100) : 0;
// 使用 \n 可以让图例显示为多行,使用空格控制对齐
return `${
name} ${
value} ${
percent}%`;
// 或者使用 HTML 标签实现更好的样式控制(需要开启 legend.useHTML)
// return `<div style="width:150px;display:flex;justify-content:space-between;">
// <span>${name}</span>
// <span>${value}</span>
// <span>${percent}%</span>
// </div>`;
},
// 如果使用 HTML 格式化,需要开启此选项
// useHTML: true,
// 调整图例项的样式
itemWidth: 12,
itemHeight: 12,
textStyle: {
fontSize: 12,
rich: {
name: {
width: 80,
align: 'left'
},
value: {
width: 40,
align: 'center'
},
percent: {
width: 40,
align: 'right'
}
}
}
},
series: [
{
type: 'pie',
radius: ['40%', '70%'], // 使用环形图,更容易查看标签
avoidLabelOverlap: true,
label: {
show: true,
position: 'outside',
formatter: '{b}\n{c} ({d}%)', // 显示名称、值和百分比
color: '#000',
backgroundColor: '#fff',
borderColor: '#aaa',
borderWidth: 1,
borderRadius: 4,
padding: [4, 8],
rich: {
name: {
fontSize: 14,
fontWeight: 'bold'
},
value: {
color: '#666'
},
percent: {
color: '#999'
}
}
},
labelLine: {
show: true,
length: 10,
length2: 20,
lineStyle: {
color: '#aaa'
}
},
data: data,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)',
},
},
},
],
};
主要修改点:
- legend 格式化:添加了
formatter
函数,自定义图例显示为 "名称 值 百分比" 的格式 - 总数值计算:使用
reduce
计算所有数据的总和,用于百分比计算 - 图例样式优化:添加了滚动功能、自定义图标和文本样式
- 饼图标签优化:改进了标签的显示格式和样式,使用
rich
文本实现更灵活的样式控制 - 环形图设计:将饼图改为环形图(设置内外半径),使标签更易于查看
如果需要更精确的对齐效果,可以考虑使用 HTML 格式化(取消注释 useHTML
和相关代码)。这样可以使用 CSS 更灵活地控制布局,但需要注意性能影响。