1.效果展示
2. 代碼
<template lang='pug'>
div.histogram-pane(:id='id')
svg.histogram-container
g.viewport
</template>
<script>
/**
* 散點圖
*/
import * as d3 from 'd3'
import { Uuid } from '@/util/common'
export default {
name: 'scatter',
data () {
return {
id: '',
width: 0,
height: 0,
xAxisWidth: 300,
yAxisHeight: 300,
margin: null,
dataSet: [
[0.5, 0.5], [0.7, 0.8], [0.4, 0.9], [0.11, 0.32], [0.88, 0.25],
[0.75, 0.12], [0.5, 0.1], [0.2, 0.3], [0.4, 0.1], [0.6, 0.7]
]
}
},
created () {
this.id = Uuid()
},
mounted () {
let width = document.getElementById(this.id).clientWidth
let height = document.getElementById(this.id).clientHeight
this.margin = { top: 60, bottom: 60, left: 60, right: 60 }
d3.select('svg').attr('width', width).attr('height', height)
d3.select('g.viewport').attr('transform', 'translate(' + this.margin.top + ',' + this.margin.left + ')')
// 縮放
const zoomed = function () {
d3.select('svg')
.select('g.viewport')
.attr('transform', d3.event.transform)
}
const zoom = d3.zoom().on('zoom', zoomed)
d3.select('svg')
.call(zoom)
.on('dblclick.zoom', null)
// 繪畫
this.draw()
},
methods: {
draw () {
let g = d3.select('g.viewport')
// 繪製座標軸
let xscale = d3.scaleLinear().domain([0, 1.2 * d3.max(this.dataSet, d => {
return d[0]
})]).range([0, this.xAxisWidth])
let xAxis = d3.axisBottom(xscale)
g.append('g')
.attr('transform', 'translate(' + 0 + ',' + this.yAxisHeight + ')')
.call(xAxis)
let yscale = d3.scaleLinear().domain([0, 1.2 * d3.max(this.dataSet, d => {
return d[1]
})]).range([this.yAxisHeight, 0])
let yAxis = d3.axisLeft(yscale)
g.append('g')
.attr('transform', 'translate(' + 0 + ',' + 0 + ')')
.call(yAxis)
// 繪製散點圖
let circle = g.selectAll('cricle').data(this.dataSet).enter().append('circle')
circle.attr('fill', 'black')
.attr('cx', d => {
return xscale(d[0])
})
.attr('cy', d => {
return this.yAxisHeight - yscale(d[1])
})
.attr('r', 5)
}
}
}
</script>
<style lang='scss' scoped>
.histogram-pane {
width: 100%;
height: 100%;
}
.histogram-container {
width: 100%;
height: 100%;
}
</style>
(1).上面的id: 即uuid爲一個隨機產生的16位字符串,同學們可以隨便用一個特殊的id表示即可,如'adfas11243'
(2).利用數據中x和y的最大值構成座標軸, 繪製半徑爲5黑色的圓表示散點數據,當然也可以加上tootip,hover的時候展示。