D3附加直线或矩形以填充饼图值

时间:2020-03-13 19:52:25

标签: d3.js svg

使用d3 v5.15.0

我正在构建一个饼图,我想在其中使用线或矩形来填充值(或展平拱形以这种方式出现?)。目前,我可以使用圆弧填充它。

已删除的图像。

import * as d3 from "d3";

const startAngle = (-40 * Math.PI) / 180;
const endAngle = (-40 * Math.PI) / 180 + 2 * Math.PI;
const width = 500;
const height = Math.min(width, 500);

function drawBenefitsValues(svg, data, startArc) {
  const radius = Math.min(width, height) / 2;
  const degreesToRadians = degrees => degrees * 0.0174533;
  const innerFactor = startArc;
  const outerFactor = value => innerFactor + value * 0.0509;
  const slice = degreesToRadians(30);

  // TODO - Is there a way to draw the path with a calculated arc and avoid the forEach?
  data.forEach((ele, idx) => {
    const id = `gBenefits${idx}`;
    const color =
      ele.benefits > 4.75
        ? "#999A57"
        : ele.benefits > 3.33
        ? "#E2B465"
        : ele.benefits > 2
        ? "#E2B465"
        : "#D3665D";
    const angleBegins = startAngle + idx * slice;
    const gridPie = d3
      .pie()
      .startAngle(angleBegins + 0.05)
      .endAngle(angleBegins + slice)
      .padAngle(0.05)
      .sort(null)
      .value(1);

    const arc = d3
      .arc()
      .innerRadius(radius * innerFactor + 1)
      .outerRadius(radius * outerFactor(ele.benefits))
      .padRadius(radius * 2.5)

    svg
      .append("g")
      .attr("id", id)
      .selectAll(`#${id}`)
      .data(gridPie([ele]))
      .join("path")
      .attr("d", arc)
      .attr("class", "benefits")
      .attr("fill", color);
  });
}

1 个答案:

答案 0 :(得分:1)

朋友帮助我提出了一种解决方案。基本上,我将弧的起点和终点设置为相同。当然,这将导致元素消失,因为没有更多的弓形,只有一条直线。然后,我添加了一个笔触以及一个笔触宽度,以在拱门外创建一种矩形。

const arc = d3
      .arc()
      .innerRadius(radius * outerFactor(ele.overuses))
      .startAngle(d => d.startAngle)
      .outerRadius(radius * innerFactor)
      .endAngle(d => d.startAngle);

svg
      .append("g")
      .attr("id", id)
      .selectAll(`#${id}`)
      .data(gridPie([ele]))
      .join("path")
      .attr("class", "benefits")
      .attr("fill", color)
      .attr("d", arc)
      .attr("stroke-width", "18")
      .attr("stroke", color);