我正在使用 d3.v4 绘制具有以下数据集的饼图:
var InternetUsage = [{usage:"no time at all", number:3},
{usage:"less than an hour a day", number:139},
{usage:"few hours a day", number:740},
{usage:"most of the day", number:122}];
Run Code Online (Sandbox Code Playgroud)
我希望每个切片的颜色都在一个范围内。但是除了显示文本标签之外,什么都不运行我的代码。根据我的假设,当我想从数据集中提取属性的值时会出现问题。Likevar pie = d3.pie().value(function(d) { return d.number ;});可能不像我预期的那样工作。但是,我不知道在这种情况下如何修复它。
我在 .js 文件中编写的完整代码是
var width = 950
var height = 500;
var radius = 250;
var svg = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height);
var g = svg.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var color = d3.scaleOrdinal(d3.schemeCategory20c);
var arc = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var label = d3.arc()
.outerRadius(radius - 40)
.innerRadius(radius - 40);
var pie = d3.pie()
.value(function(d) { return d.number ;});
var InternetUsage = [{usage:"no time at all", number:3},
{usage:"less than an hour a day", number:139},
{usage:"few hours a day", number:740},
{usage:"most of the day", number:122}];
var arc = g.selectAll(".arc")
.data(pie(InternetUsage))
.enter()
.append("g")
.attr("class", "arc");
arc.append("path")
.attr("stroke", "#fff")
.style("fill", function(d,i) { return color(InternetUsage[i].usage); });
arc.append("text")
.attr("transform", function(d){return "translate(" + label.centroid(d) + ")"; })
.style("font-size","10px")
.attr("dy", "0.35em")
.attr('text-anchor', 'middle')
.text(function(d,i) {return InternetUsage[i].usage; });
Run Code Online (Sandbox Code Playgroud)
您忘记d为您的path元素指定属性:
arc.append("path")
.attr("stroke", "#fff")
.attr("d", path) // <== !!!
.style("fill", function(d,i) { return color(InternetUsage[i].usage); });
Run Code Online (Sandbox Code Playgroud)
请注意,我将您的路径生成器函数重命名为path(您将其称为arc),因为您对 DOM 节点 ( var arc = g.selectAll(".arc")...)使用了相同的变量名。
var path = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0);
Run Code Online (Sandbox Code Playgroud)
工作演示:
arc.append("path")
.attr("stroke", "#fff")
.attr("d", path) // <== !!!
.style("fill", function(d,i) { return color(InternetUsage[i].usage); });
Run Code Online (Sandbox Code Playgroud)
var path = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
883 次 |
| 最近记录: |