vue实现散点图源码
vue实现散点图源码
在Vue中实现散点图,可以使用ECharts或Chart.js等流行的图表库。以下是两种常见库的实现方法:
使用ECharts实现散点图
安装ECharts依赖:
npm install echarts --save
在Vue组件中使用:
<template>
<div ref="scatterChart" style="width: 600px; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
mounted() {
this.initScatterChart();
},
methods: {
initScatterChart() {
const chartDom = this.$refs.scatterChart;
const myChart = echarts.init(chartDom);
const option = {
xAxis: {},
yAxis: {},
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);
}
}
};
</script>
使用Chart.js实现散点图
安装Chart.js依赖:
npm install chart.js --save
在Vue组件中使用:
<template>
<canvas ref="scatterChart"></canvas>
</template>
<script>
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);
export default {
mounted() {
this.initScatterChart();
},
methods: {
initScatterChart() {
const ctx = this.$refs.scatterChart.getContext('2d');
new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'Scatter Dataset',
data: [{
x: -10,
y: 0
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}, {
x: 0.5,
y: 5.5
}],
backgroundColor: 'rgb(255, 99, 132)'
}]
},
options: {
scales: {
x: {
type: 'linear',
position: 'bottom'
}
}
}
});
}
}
};
</script>
自定义散点图组件
如果需要更灵活的散点图,可以创建一个可复用的Vue组件:

<template>
<div :style="{ width: width, height: height }" ref="chart"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
props: {
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '400px'
},
data: {
type: Array,
required: true
}
},
watch: {
data: {
handler(newVal) {
this.updateChart(newVal);
},
deep: true
}
},
mounted() {
this.initChart();
},
methods: {
initChart() {
this.chart = echarts.init(this.$refs.chart);
this.updateChart(this.data);
},
updateChart(data) {
const option = {
xAxis: {},
yAxis: {},
series: [{
type: 'scatter',
data: data,
symbolSize: function (data) {
return Math.sqrt(data[1]) * 5;
}
}]
};
this.chart.setOption(option);
}
},
beforeDestroy() {
if (this.chart) {
this.chart.dispose();
}
}
};
</script>
这些示例展示了在Vue项目中实现散点图的不同方法,可以根据项目需求选择合适的方案。ECharts提供了更丰富的配置选项和交互功能,而Chart.js则更轻量且易于使用。






