【问题标题】:How to implement D3 donut chart?如何实现 D3 圆环图?
【发布时间】:2016-03-12 04:45:27
【问题描述】:

如何使用 D3.js 实现这个圆环图?有人请帮帮我。

我尝试了下面的代码,但我在设计中遇到了圆角半径和灰色弧线的问题:

Javascript:

var dataset = {
  apples: [53245, 28479, 19697, 24037, 40245],
};

var width = 460,
    height = 300,
    radius = Math.min(width, height) / 2;

var color = d3.scale.category20();

var pie = d3.layout.pie()
    .sort(null);

var arc = d3.svg.arc()
    .innerRadius(radius - 100)
    .outerRadius(radius - 50);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var path = svg.selectAll("path")
    .data(pie(dataset.apples))
  .enter().append("path")
    .attr("fill", function(d, i) { return color(i); })
    .attr("d", arc);

CSS:

body {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  margin: auto;
  position: relative;
  width: 960px;
}

text {
  font: 10px sans-serif;
}

jsfiddle.net/gregfedorov/qh9x5/9

【问题讨论】:

  • 在询问应该如何实施之前,请先尝试一下。甜甜圈图有很多 d3 示例。尝试修改这些
  • 我试过了。但我在设计中遇到拐角半径和灰色弧线的问题。我也试过这个。并尝试修改。 jsfiddle.net/gregfedorov/qh9x5/9

标签: javascript d3.js svg


【解决方案1】:

你可以这样做:

首先定义数据:

var dataset = [{
  color: "red",
  value: 11
}, {
  color: "blue",
  value: 20
}, {
  color: "yellow",
  value: 12
}, {
  color: "transparent",//transparent for the gray part
  value: 22
}];

为灰色部分定义圆弧:

var arc1 = d3.svg.arc()
  .innerRadius(radius - 18)
  .outerRadius(radius - 13);

为其他颜色的甜甜圈部分定义圆弧:

var arc = d3.svg.arc()
  .innerRadius(radius - 20)
  .outerRadius(radius - 10);

现在像这样在背景中制作灰色甜甜圈:

var path = svg.selectAll(".background")
  .data(pie([{
    color: "gray",
    value: 1
  }]))
  .enter().append("path")
  .attr("class", "background")
  .attr("fill", function(d, i) {
    return d.data.color;
  })
  .attr("d", arc1);

现在制作彩色甜甜圈部分(数据集中将有一个颜色为transparent 的部分将显示后面的灰色甜甜圈)想法是将一个甜甜圈图叠加在另一个上。

var path = svg.selectAll(".foreground")
  .data(pie(dataset))
  .enter().append("path")
  .attr("class", "foreground")
  .attr("fill", function(d, i) {
    return d.data.color;
  })
  .attr("d", arc);

工作示例here

【讨论】:

  • 谢谢西里尔。正如我在上述评论中提到的主要问题是使红色和绿色的角落变成圆形。你能帮我解决这个问题吗? @Cyril
  • Rounded 使用 stroke-linecap="round" 做到了这一点 jsfiddle.net/cyril123/3Ly934g0
猜你喜欢
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-18
  • 2013-11-12
相关资源
最近更新 更多