ECharts图例的展示区域没这么大,如何自定义ECharts提示框的位置,和自定义内容呢。
原本效果:图例到处跑,显示不全。
修改后效果:只在显示区域展示。
ECharts的tooltip组件远比表面看起来强大。以下是我们示例中的配置:
//原本代码:
tooltip: {
trigger: "item",
}
//自定义代码:
tooltip: {
trigger: "item",
formatter: function (params: any) {
return `${params.marker} ${params.name}<br/>收入: ${params.value}元<br/>占比: ${params.percent}%`;
},
}
ECharts的tooltip组件用于展示数据项的详细信息,以下是其主要配置字段:
字段 | 类型 | 默认值 | 描述 |
---|---|---|---|
trigger | string | 'item' | 触发类型,可选'item'(数据项)、'axis'(坐标轴)或'none'(不触发) |
formatter | Function|string | null | 内容格式化器,支持字符串模板和回调函数 |
backgroundColor | string | 'rgba(50,50,50,0.7)' | 提示框背景颜色 |
borderColor | string | '#333' | 提示框边框颜色 |
textStyle | Object | {color:'#fff'} | 文本样式配置对象 |
position | string|Array|Function | null | 提示框位置,可设为绝对坐标或相对位置的百分比 |
confine | boolean | false | 是否将提示框限制在图表区域内 |
formatter是tooltip中最强大的配置项,支持多种格式化方式:
// 字符串模板方式
formatter: '{a} <br/>{b} : {c}'
// 回调函数方式(推荐)
formatter: function(params) {
// params可以是单个对象或对象数组(多系列数据)
return `
<div class="tooltip-title">${params.name}</div>
<div class="tooltip-value">值: ${params.value}</div>
<div class="tooltip-percent">占比: ${params.percent}%</div>
`;
}
formatter回调参数包含以下重要属性:
componentType
: 组件类型(如'series')seriesType
: 系列类型(如'pie'、'line')seriesIndex
: 系列索引seriesName
: 系列名称name
: 数据名称dataIndex
: 数据索引data
: 数据对象value
: 数值(Array或多维时)color
: 数据项颜色percent
: 饼图等占比百分比marker
: 颜色标记的HTML字符串//原本代码:
legend: {
left: "center",
}
//自定义代码:
legend: {
left: "center",
top: "bottom",
orient: "horizontal",
itemWidth: 12,
itemHeight: 12,
textStyle: {
fontSize: 12,
color: "#333",
},
}
字段 | 类型 | 默认值 | 描述 |
---|---|---|---|
orient | string | 'horizontal' | 布局方向,'horizontal'或'vertical' |
left | string|number | 'auto' | 离容器左侧的距离 |
top | string|number | 'auto' | 离容器顶部的距离 |
right | string|number | 'auto' | 离容器右侧的距离 |
bottom | string|number | 'auto' | 离容器底部的距离 |
itemWidth | number | 25 | 图例图形宽度 |
itemHeight | number | 14 | 图例图形高度 |
itemGap | number | 10 | 图例每项间隔 |
selectedMode | boolean|string | true | 选择模式,可控制系列显示状态 |
textStyle | Object | {color:'#333'} | 文本样式配置 |
formatter | string|Function | null | 图例文本格式化器 |
const option = {
legend: {
left: "center",
top: "bottom",
orient: "horizontal",
itemWidth: 12,
itemHeight: 12,
textStyle: {
fontSize: 12,
color: "#333",
},
},
tooltip: {
trigger: "item",
formatter: function (params: any) {
return `${params.marker} ${params.name}<br/>收入: ${params.value}元<br/>占比: ${params.percent}%`;
},
},
title: {
text: "收入分析",
left: "left",
top: 20,
textStyle: {
color: "#000",
fontSize: 12,
fontWeight: "normal",
},
},
toolbox: {
show: true,
},
series: [
{
name: "收入分析",
type: "pie",
radius: [30, 100],
center: ["50%", "50%"],
roseType: "area",
itemStyle: {
borderRadius: 8,
},
data: ['数组'],
},
],
};
ECharts 5.x版本对tooltip和legend的兼容性:
本文示例基于ECharts 5.4+版本,部分特性在旧版本中可能不支持。具体实现请参考官方文档和实际业务需求。
您好,我是肥晨。
欢迎关注我获取前端学习资源,日常分享技术变革,生存法则;行业内幕,洞察先机。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。