ECharts中的markPoint使用,最大值,最小值,展示label数值
什么是 markPoint?
markPoint
是 ECharts 中用于标注图表中特殊数据点的配置项。通过 markPoint
,可以在图表中突出显示特定的数据点,例如最大值、最小值、平均值等,并可以自定义标注的样式和位置。
commonMarketPoint 方法详解
为了方便使用 markPoint
标注最大值和最小值,我们可以封装一个名为 commonMarketPoint
的方法。该方法接收一个 PointProps
类型的对象作为参数,并返回一个配置对象,用于 ECharts 的 markPoint
配置项。
PointProps 接口定义
首先,我们定义一个 PointProps
接口,用于约束 commonMarketPoint
方法的参数类型:
interface PointProps {symbolSize?: number; // 标注点的大小max?: { color?: string; borderColor?: string; borderWidth?: number }; // 最大值标注的样式min?: { color?: string; borderColor?: string; borderWidth?: number }; // 最小值标注的样式showValue?: boolean; // 控制是否显示数值标签valuePrecision?: number; // 控制数值的精度(0为整数,2为两位小数)maxPosition?: string; // 最大值标注的位置minPosition?: string; // 最小值标注的位置
}
commonMarketPoint 方法实现
接下来,我们实现 commonMarketPoint
方法:
// 最大值为红点,最小值为绿点
export const commonMarketPoint = ({symbolSize = 6,max = { color: '#FF3E3E', borderColor: '#FFF', borderWidth: 1 },min = { color: '#2FD380', borderColor: '#FFF', borderWidth: 1 },showValue = false, // 默认不显示数值标签valuePrecision = 2, // 默认保留两位小数maxPosition = 'top',minPosition = 'bottom',
}: PointProps) => {return {data: [{type: 'max',name: '最大值',symbol: 'circle', // 设置为圆形symbolSize, // 圆点大小label: {show: showValue,position: maxPosition,formatter: (params: any) => params.value.toFixed(valuePrecision),},itemStyle: {borderColor: max?.borderColor,borderWidth: max?.borderWidth,color: max?.color,shadowColor: '#fff',shadowBlur: 2,},},{type: 'min',name: '最小值',symbol: 'circle',symbolSize,label: {show: showValue,position: minPosition,formatter: (params: any) => params.value.toFixed(valuePrecision),},itemStyle: {borderColor: min?.borderColor,borderWidth: min?.borderWidth,color: min?.color,shadowColor: '#fff',shadowBlur: 2,},},],};
};
参数说明
symbolSize
:标注点的大小,默认为 6。max
:最大值标注的样式,包括颜色、边框颜色和边框宽度。min
:最小值标注的样式,包括颜色、边框颜色和边框宽度。showValue
:是否显示数值标签,默认为 false。valuePrecision
:数值的精度,默认为 2,表示保留两位小数。maxPosition
:最大值标注的位置,默认为 ‘top’。minPosition
:最小值标注的位置,默认为 ‘bottom’。
使用示例
接下来,我们通过一个示例来演示如何使用 commonMarketPoint
方法。
HTML 代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>ECharts markPoint 示例</title><!-- 引入 ECharts --><script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
</head>
<body><!-- 为 ECharts 准备一个具备大小(宽高)的 DOM --><div id="main" style="width: 600px;height:400px;"></div><script src="index.js"></script>
</body>
</html>
JavaScript 代码
// 引入 commonMarketPoint 方法
import { commonMarketPoint } from './commonMarketPoint.js';
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 指定图表的配置项和数据
var option = {title: {text: 'ECharts markPoint 示例'},tooltip: {},xAxis: {data: ['A', 'B', 'C', 'D', 'E', 'F']},yAxis: {},series: [{name: '销量',type: 'bar',data: [5, 20, 36, 10, 10, 20],markPoint: commonMarketPoint({showValue: true,valuePrecision: 2,})}]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
效果展示
运行上述代码后,你将看到一个柱状图,并在最大值和最小值处显示红点和绿点,并标注数值。