Vue echarts实现散点图
Vue 中实现 ECharts 散点图
安装 ECharts 依赖
在 Vue 项目中通过 npm 或 yarn 安装 ECharts:
npm install echarts --save
# 或
yarn add echarts
引入 ECharts 并初始化图表
在 Vue 组件中引入 ECharts 并创建散点图实例:

import * as echarts from 'echarts';
export default {
mounted() {
this.initChart();
},
methods: {
initChart() {
const chartDom = document.getElementById('scatter-chart');
const myChart = echarts.init(chartDom);
const option = {
xAxis: {},
yAxis: {},
series: [{
symbolSize: 20,
data: [
[10, 20],
[15, 30],
[25, 10],
[35, 40],
[45, 15]
],
type: 'scatter'
}]
};
myChart.setOption(option);
}
}
}
模板中添加容器
在组件的模板中添加一个容器元素用于渲染图表:
<template>
<div id="scatter-chart" style="width: 600px; height: 400px;"></div>
</template>
响应式调整
监听窗口大小变化并调整图表尺寸:

methods: {
initChart() {
// ...初始化代码...
window.addEventListener('resize', () => {
myChart.resize();
});
}
},
beforeDestroy() {
window.removeEventListener('resize', () => {});
}
自定义散点图样式
通过配置项自定义散点颜色、大小和形状:
series: [{
symbolSize: (value) => {
return value[1] * 0.5; // 根据 y 值动态调整大小
},
itemStyle: {
color: '#c23531'
},
data: [
[10, 20, 'A'], // 第三个参数可用于 tooltip 显示
[15, 30, 'B'],
[25, 10, 'C']
],
type: 'scatter'
}]
添加交互功能
配置 tooltip 和 dataZoom 增强交互性:
option: {
tooltip: {
formatter: (params) => {
return `值: ${params.value[0]}, ${params.value[1]}`;
}
},
dataZoom: [
{
type: 'slider',
xAxisIndex: 0
},
{
type: 'slider',
yAxisIndex: 0
}
]
}






