簡(jiǎn)單的餅圖嫂粟,D3js v4版本畫的星虹,后續(xù)會(huì)更新一些復(fù)雜的例子,敬請(qǐng)關(guān)注
效果圖:
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="http://d3js.org/d3.v4.min.js"></script>
<style>
#container {
margin: 0 auto;
}
</style>
</head>
<body>
<div id="container" width="700" height="400"></div>
</body>
</html>
<script>
let container = d3.select("#container")
let width = container.attr("width")
let height = container.attr("height")
let padding = 30
let datas = [
{ name: "java", value: 0.4 },
{ name: "html", value: 0.14 },
{ name: "javascript", value: 0.36 },
{ name: "python", value: 0.1 }
]
let dataset = [50, 26, 18, 58, 48];
let svg = d3.select("#container")
.append("svg")
.attr("width", width)
.attr("height", height)
let colorScale = d3.scaleOrdinal()
.domain([0, datas.length])
.range(d3.schemeCategory10)
let pie = d3.pie()
let innerR = 0
let outR = 100
let arc_generator = d3.arc()
.innerRadius(innerR)
.outerRadius(outR)
let pieData = pie(dataset)
let g = svg.selectAll("g")
.data(pieData)
.enter()
.append("g")
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')')
g.append("path")
.attr("d", d => arc_generator(d))
.attr("fill", (d, i) => colorScale(i))
g.append("text")
.attr("transform", d => {
return "translate(" + arc_generator.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(d => d.value)
</script>