vue实现散点图源码
以下是一个基于 Vue 和 ECharts 实现散点图的完整源码示例,包含配置和交互逻辑:
安装依赖
确保已安装 Vue 和 ECharts:
npm install vue echarts
基础实现代码
<template>
<div ref="scatterChart" style="width: 600px; height: 400px"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
name: 'ScatterChart',
mounted() {
this.initChart();
},
methods: {
initChart() {
const chartDom = this.$refs.scatterChart;
const myChart = echarts.init(chartDom);
const option = {
title: {
text: '散点图示例'
},
tooltip: {},
xAxis: {
name: 'X轴'
},
yAxis: {
name: 'Y轴'
},
series: [{
symbolSize: 20,
data: [
[10.0, 8.04],
[8.0, 6.95],
[13.0, 7.58],
[9.0, 8.81],
[11.0, 8.33],
[14.0, 9.96],
[6.0, 7.24],
[4.0, 4.26],
[12.0, 10.84],
[7.0, 4.82],
[5.0, 5.68]
],
type: 'scatter'
}]
};
myChart.setOption(option);
// 响应式调整
window.addEventListener('resize', function() {
myChart.resize();
});
}
}
};
</script>
进阶功能实现
添加动态数据更新和点击事件:
methods: {
initChart() {
// ...基础配置同前
// 动态更新示例
setInterval(() => {
const newData = this.generateRandomData();
myChart.setOption({
series: [{
data: newData
}]
});
}, 2000);
// 点击事件
myChart.on('click', (params) => {
console.log('点击数据点:', params.data);
});
},
generateRandomData() {
return Array.from({length: 10}, () => [
Math.random() * 20,
Math.random() * 10
]);
}
}
样式优化配置
option = {
// ...其他配置
series: [{
itemStyle: {
color: function(params) {
const colorList = ['#c23531','#2f4554','#61a0a8'];
return colorList[params.dataIndex % 3];
}
},
label: {
show: true,
formatter: ({data}) => `(${data[0]}, ${data[1]})`
}
}]
}
注意事项
-
需要在
mounted生命周期初始化图表,确保 DOM 已渲染 -
组件销毁时应移除事件监听和图表实例:
beforeDestroy() { if (this.myChart) { this.myChart.dispose(); window.removeEventListener('resize', this.resizeHandler); } } -
大数据量场景建议启用渐进渲染:

series: [{ progressive: 1000, progressiveThreshold: 3000 }]






