Vue echarts实现散点图
安装依赖
确保项目中已安装Vue和ECharts。通过npm或yarn安装ECharts:
npm install echarts --save
引入ECharts
在Vue组件中引入ECharts核心模块:
import * as echarts from 'echarts';
准备DOM容器
在模板中定义一个具有明确宽高的DOM元素作为图表容器:
<template>
<div ref="chartContainer" style="width: 600px; height: 400px;"></div>
</template>
初始化图表
在mounted生命周期钩子中初始化图表,并绑定到DOM容器:
mounted() {
this.initChart();
},
methods: {
initChart() {
const chartDom = this.$refs.chartContainer;
const myChart = echarts.init(chartDom);
}
}
配置散点图选项
设置散点图的基本配置项,包括数据集、坐标轴、系列类型等:
const option = {
xAxis: {
type: 'value',
scale: true
},
yAxis: {
type: 'value',
scale: true
},
series: [{
type: 'scatter',
data: [
[10, 20],
[15, 30],
[20, 25],
[30, 40]
],
symbolSize: 10
}]
};
渲染图表
将配置项应用到图表实例并渲染:

myChart.setOption(option);
响应式调整
监听窗口变化事件,实现图表自适应:
window.addEventListener('resize', () => {
myChart.resize();
});
销毁实例
在组件销毁时移除监听并释放图表资源:
beforeDestroy() {
window.removeEventListener('resize', this.resizeHandler);
if (this.myChart) {
this.myChart.dispose();
}
}
完整组件示例
整合上述代码的完整Vue组件示例:

<template>
<div ref="chartContainer" style="width: 600px; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
data() {
return {
myChart: null
};
},
mounted() {
this.initChart();
this.resizeHandler = () => this.myChart?.resize();
window.addEventListener('resize', this.resizeHandler);
},
methods: {
initChart() {
const chartDom = this.$refs.chartContainer;
this.myChart = echarts.init(chartDom);
const option = {
xAxis: { type: 'value', scale: true },
yAxis: { type: 'value', scale: true },
series: [{
type: 'scatter',
data: [[10,20], [15,30], [20,25], [30,40]],
symbolSize: 10
}]
};
this.myChart.setOption(option);
}
},
beforeDestroy() {
window.removeEventListener('resize', this.resizeHandler);
this.myChart?.dispose();
}
};
</script>
进阶配置
可通过以下方式增强散点图功能:
-
添加提示框组件:
tooltip: { trigger: 'item', formatter: params => { return `X: ${params.value[0]}<br/>Y: ${params.value[1]}`; } } -
设置视觉映射:
visualMap: { dimension: 1, min: 10, max: 50, inRange: { color: ['#50a3ba', '#eac736', '#d94e5d'] } } -
添加动画效果:
series: [{ animationDuration: 2000, animationEasing: 'elasticOut' }]






