javascript - 如何实现D3圆环图?

标签 javascript d3.js svg

Design

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

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

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

最佳答案

你可以这样做:

首先定义数据:

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);

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

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

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

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);

现在制作彩色 donut 部分(数据集中会有一个颜色为透明的部分,它将显示后面的灰色 donut )想法是将一个 donut chart 叠加在另一个上面。

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

关于javascript - 如何实现D3圆环图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35953877/

相关文章:

javascript - 如何在 JavaScript 中每次鼠标滚动时使页面滚动预先固定的高度?

javascript - 需要连接d3中不同圆形填充布局的两个节点

javascript - 矩形碰撞检测d3js

javascript - d3.js 和 geojson map 抛出错误

javascript - 具有多个矢量图层的 OpenLayers map 使整个页面在 chrome 中闪烁

javascript - 多个 <li> 的鼠标悬停

javascript - 如果react-router-dom不匹配任何路由,则页面重新加载

javascript - 使用选项卡名称而不是选项卡 ID 自动选择 HTML 按钮上的选项卡单击

JavaScript - 动态 SVG - onload 属性 - 未触发事件

javascript - SVG API : length of a single segment