vue实现散点图源码
以下是一个基于 Vue 和 ECharts 实现散点图的完整源码示例,分为组件封装和基础使用两部分:
安装依赖
确保项目中已安装 ECharts 和 Vue-ECharts:

npm install echarts vue-echarts
封装可复用的散点图组件
创建 ScatterChart.vue 文件:
<template>
<v-chart
class="scatter-chart"
:option="option"
:autoresize="true"
/>
</template>
<script>
import { use } from 'echarts/core';
import { ScatterChart } from 'echarts/charts';
import {
GridComponent,
TooltipComponent,
LegendComponent,
TitleComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import VChart from 'vue-echarts';
use([
ScatterChart,
GridComponent,
TooltipComponent,
LegendComponent,
TitleComponent,
CanvasRenderer
]);
export default {
components: { VChart },
props: {
data: {
type: Array,
required: true
},
xAxisName: {
type: String,
default: 'X轴'
},
yAxisName: {
type: String,
default: 'Y轴'
}
},
computed: {
option() {
return {
title: {
text: '散点图示例'
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'
}
},
legend: {
data: ['数据集1']
},
xAxis: {
name: this.xAxisName,
type: 'value'
},
yAxis: {
name: this.yAxisName,
type: 'value'
},
series: [{
name: '数据集1',
type: 'scatter',
symbolSize: 10,
data: this.data,
itemStyle: {
color: '#5470c6'
}
}]
};
}
}
};
</script>
<style scoped>
.scatter-chart {
width: 100%;
height: 400px;
}
</style>
在父组件中使用
在需要展示散点图的页面中引入组件:

<template>
<div>
<scatter-chart
:data="chartData"
x-axis-name="温度(℃)"
y-axis-name="销量(件)"
/>
</div>
</template>
<script>
import ScatterChart from './components/ScatterChart.vue';
export default {
components: { ScatterChart },
data() {
return {
chartData: [
[10, 35],
[15, 48],
[20, 60],
[25, 72],
[30, 85],
[35, 92],
[40, 78]
]
};
}
};
</script>
高级配置选项(可选)
若需要更复杂的散点图,可修改 option 计算属性:
option() {
return {
// ...其他配置
series: [{
type: 'scatter',
symbolSize: function (data) {
return Math.sqrt(data[1]) * 2;
},
label: {
show: true,
formatter: function (param) {
return param.data[0] + ',' + param.data[1];
}
},
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}]
};
}
动态更新数据
通过 Vue 的响应式特性,当数据变化时图表会自动更新:
// 在父组件中
methods: {
updateData() {
this.chartData = [
...this.chartData,
[Math.random() * 50, Math.random() * 100]
];
}
}






