<!DOCTYPE html>
<html lang="en">
<head>
<title>d3</title>
<script type="text/javascript" src="./d3@7.js"></script>
<style type="text/css">
</style>
</head>
<body>
<div id="chart"></svg>
<script type="text/javascript">
const width = 800
const height = 500
const radius = Math.min(width, height) / 2.5
const donutWidth = 75
const legendRectSize = 18
const legendSpacing = 4
const data = [
{ label: 'A', value: 50 },
{ label: 'B', value: 30 },
{ label: 'C', value: 20 },
{ label: 'D', value: 10 },
{ label: 'E', value: 5 }
]
const svg = d3.select('#chart')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', `translate(${width / 2}, ${height / 2})`)
const color = d3.scaleOrdinal(d3.schemeCategory10)
const arc = d3.arc()
.innerRadius(radius - donutWidth)
.outerRadius(radius)
const pie = d3.pie()
.value(d => d.value)
.sort(null)
const path = svg.selectAll('path')
.data(pie(data))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', (d, i) => color(i))
.on('mouseover', function (d) {
d3.select(this).transition()
.duration(200)
.attr('d', d3.arc()
.innerRadius(radius - donutWidth + 10)
.outerRadius(radius + 10)
)
})
.on('mouseout', function (d) {
d3.select(this).transition()
.duration(200)
.attr('d', arc)
})
const text = svg.selectAll('text')
.data(pie(data))
.enter()
.append('text')
.attr('transform', d => `translate(${arc.centroid(d)})`)
.attr('dy', '.35em')
.text(d => d.data.label)
.style('text-anchor', 'middle')
const legend = svg.selectAll('.legend')
.data(color.domain())
.enter()
.append('g')
.attr('class', 'legend')
.attr('transform', (d, i) => {
const height = legendRectSize + legendSpacing
const offset = height * color.domain().length / 2
const horz = -2 * legendRectSize
const vert = i * height - offset
return `translate(${horz}, ${vert})`
})
legend.append('rect')
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.style('fill', color)
.style('stroke', color)
legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing)
.text(d => d)
</script>
</body>
</html>
2.png
网友评论