vue实现散点图源码
以下是一个基于 Vue 和 ECharts 实现散点图的完整源码示例,分为组件封装和基础使用两部分:
安装依赖
确保项目中已安装 ECharts 和 Vue-ECharts:
npm install echarts vue-echarts
封装可复用的散点图组件
创建 ScatterChart.vue 文件:
<template>
<v-chart class="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: {
chartData: {
type: Array,
default: () => [
[10, 20],
[15, 30],
[20, 25]
]
},
xAxisName: {
type: String,
default: "X轴"
},
yAxisName: {
type: String,
default: "Y轴"
}
},
computed: {
option() {
return {
title: {
text: "散点图示例"
},
tooltip: {
trigger: "axis",
axisPointer: {
type: "cross"
}
},
xAxis: {
name: this.xAxisName,
type: "value"
},
yAxis: {
name: this.yAxisName,
type: "value"
},
series: [
{
type: "scatter",
symbolSize: 10,
data: this.chartData,
itemStyle: {
color: "#5470c6"
}
}
]
};
}
}
};
</script>
<style scoped>
.chart {
height: 400px;
width: 100%;
}
</style>
在父组件中使用
示例父组件 App.vue:
<template>
<div id="app">
<scatter-chart
:chart-data="dataPoints"
x-axis-name="商品价格"
y-axis-name="销量"
/>
</div>
</template>
<script>
import ScatterChart from "./components/ScatterChart.vue";
export default {
components: { ScatterChart },
data() {
return {
dataPoints: [
[12.5, 156],
[24.8, 98],
[18.6, 120],
[30.2, 65],
[15.3, 145]
]
};
}
};
</script>
动态更新数据示例
可通过方法更新数据:
methods: {
updateData() {
this.dataPoints = [
[Math.random() * 30, Math.random() * 200],
[Math.random() * 30, Math.random() * 200],
[Math.random() * 30, Math.random() * 200]
];
}
}
自定义配置项
支持通过 props 传递完整配置:
props: {
customOption: {
type: Object,
default: null
}
},
computed: {
option() {
return this.customOption || {
// 默认配置
};
}
}
响应式设计
组件内置了 autoresize 属性,当容器尺寸变化时会自动调整图表大小。如需手动控制,可调用:
this.$refs.chart.resize();
该实现包含完整的类型定义、响应式设计和配置灵活性,可直接集成到 Vue 2/3 项目中。







