我对d3.js
有疑问我们假设我有这些数据:
A A B K J I O N P B N J D G R X S M M Y Y D J B B N N S B N R N E B B D D Y Y Y Y B B O O
我想得到每个字母的频率计数,并用D3.js
制作一个饼图答案 0 :(得分:1)
您不需要d3
进行计数,只需简单的JavaScript:
var string = "A A B K J I O N P B N J D G R X S O M H Y D J B T N Y S B N R N E B U D B G D G Y F T K O";
var counts = {};
string.split(" ").forEach(function(d) {
if (!counts[d]) {
counts[d] = 0;
}
counts[d]++;
});
从那里饼图变得非常棒:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var string = "A A B K J I O N P B N J D G R X S O M H Y D J B T N Y S B N R N E B U D B G D G Y F T K O";
var counts = {};
string.split(" ").forEach(function(d) {
if (!counts[d]) {
counts[d] = 0;
}
counts[d]++;
});
var data = d3.entries(counts);
console.log(data)
var width = 360;
var height = 360;
var radius = Math.min(width, height) / 2;
var color = d3.scaleOrdinal(d3.schemeCategory20b);
var svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + (width / 2) +
',' + (height / 2) + ')');
var arc = d3.arc()
.innerRadius(0)
.outerRadius(radius);
var pie = d3.pie()
.value(function(d) {
return d.value;
})
.sort(null);
var path = svg.selectAll('path')
.data(pie(data))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return color(d.data.key);
});
</script>
</body>
</html>