一. api简介
为了画饼状图需要知道了解以下知识点:
1.弧生成器
(1). 官方api带参或不带参数效果一样:innerRadius(num)-内半径;outerRadius(num)-外半径;
var arc = d3.arc() .innerRadius(0) .outerRadius(100) .startAngle(0) .endAngle(Math.PI / 2); arc(); // "M0,-100A100,100,0,0,1,100,0L0,0Z"
let arc = d3.arc(); arc({ innerRadius: 0, outerRadius: 100, startAngle: 0, endAngle: Math.PI / 2 }); //
或者:
let arc = d3.arc() .innerRadius(0) .outerRadius(100) .startAngle(0) .endAngle(Math.PI / 2); arc(); // "M0,-100A100,100,0,0,1,100,0L0,0Z"
(2) arc.centroid(arguments…)
设置弧形中心坐标点
Computes the midpoint [x, y] of the center line of the arc: (startAngle + endAngle) / 2 and (innerRadius + outerRadius) / 2.
2. 饼状图生成器
d3.pie()饼状图生成器; d3.pie()(data)-弧形数据
3. 离散色彩生成器
d3.schemeCategory10 ---- [color1, color2...]
二.Vue中使用
<template lang='pug'>
div.pie-pane(:id="id")
svg
</template>
<script>
/**
* 饼状图
*/
import * as d3 from 'd3'
export default {
name: 'Scale',
data() {
return {
id: ''
}
},
methods: {
uuid () {
function s4 () {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1)
}
return (
s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4()
)
}
},
created() {
this.id = this.uuid()
},
mounted () {
//1.创建svg画布
let marge = { top: 160, bottom: 60, left: 160, right: 60 }
let width = document.getElementById(this.id).clientWidth
let height = document.getElementById(this.id).clientHeight
const svg = d3.select(this.$el).select('svg').attr('width', width).attr('height', height)
let g = svg.append('g').attr('transform', 'translate(' + marge.top + ',' + marge.left + ')')
//2.设置颜色比例尺
let dataSet = [100, 200, 500]
let colorScale = d3.scaleOrdinal()
.domain(d3.range(dataSet.length))
.range(d3.schemeCategory10)
//3.新建弧形生成器
let innerRadius = 0
let outerRadius = 100
let arc_generator = d3.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius)
//4.利用饼状图生成器转换成画弧形需要的数据
// let pie = d3.pie()
// let arcData = pie(dataSet)
let arcData = d3.pie()(dataSet)
console.log(arcData)
//5.为每一个扇形建立分组<g>
let gs = g.selectAll('.g')
.data(arcData)
.enter()
.append('g')
//6.绘制扇形
gs.append('path')
.attr('d', function(d) {
return arc_generator(d)
})
.attr('fill', function(d, i) {
return colorScale(i)
})
//7.绘制文字
gs.append('text')
.attr('transform', function(d) {
//位置设在中心处
return 'translate('+ arc_generator.centroid(d) +')'
})
.attr('text-anchor', 'middle')
.text(function(d) {
return d.data
})
}
}
</script>
<style lang='scss' scoped>
.pie-pane {
width: 600px;
height: 600px;
}
</style>