vue实现散点图
Vue 实现散点图的方法
使用 ECharts 库
安装 ECharts 依赖:
npm install echarts --save
在 Vue 组件中引入并使用:
<template>
<div ref="chart" style="width: 600px; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
mounted() {
this.initChart();
},
methods: {
initChart() {
const chartDom = this.$refs.chart;
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
创建散点图组件:
<template>
<canvas ref="chart"></canvas>
</template>
<script>
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);
export default {
mounted() {
this.renderChart();
},
methods: {
renderChart() {
const ctx = this.$refs.chart.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
}],
backgroundColor: 'rgb(255, 99, 132)'
}]
},
options: {
scales: {
x: {
type: 'linear',
position: 'bottom'
}
}
}
});
}
}
};
</script>
使用 D3.js 实现更高级定制
安装 D3.js 依赖:

npm install d3 --save
创建自定义散点图组件:
<template>
<svg ref="svg" width="500" height="300"></svg>
</template>
<script>
import * as d3 from 'd3';
export default {
mounted() {
this.drawScatterPlot();
},
methods: {
drawScatterPlot() {
const data = [
{ x: 10, y: 20 },
{ x: 20, y: 50 },
{ x: 40, y: 10 },
{ x: 60, y: 40 },
{ x: 80, y: 20 }
];
const svg = d3.select(this.$refs.svg);
const margin = { top: 20, right: 20, bottom: 30, left: 40 };
const width = +svg.attr('width') - margin.left - margin.right;
const height = +svg.attr('height') - margin.top - margin.bottom;
const x = d3.scaleLinear()
.domain([0, 100])
.range([0, width]);
const y = d3.scaleLinear()
.domain([0, 60])
.range([height, 0]);
const g = svg.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`);
g.append('g')
.attr('transform', `translate(0,${height})`)
.call(d3.axisBottom(x));
g.append('g')
.call(d3.axisLeft(y));
g.selectAll('circle')
.data(data)
.enter().append('circle')
.attr('cx', d => x(d.x))
.attr('cy', d => y(d.y))
.attr('r', 5)
.attr('fill', 'steelblue');
}
}
};
</script>
响应式处理
添加窗口大小变化时的图表重绘:
methods: {
initChart() {
// ...之前的图表初始化代码
window.addEventListener('resize', () => {
myChart.resize();
});
}
},
beforeDestroy() {
window.removeEventListener('resize', this.resizeHandler);
}
数据动态更新
实现数据动态更新功能:
methods: {
updateData(newData) {
this.chart.setOption({
series: [{
data: newData
}]
});
}
}






