【问题标题】:d3js Pie chart gradientd3js 饼图渐变
【发布时间】:2016-06-08 22:26:27
【问题描述】:

一直在尝试构建一个带有平滑渐变的饼图/甜甜圈图,但发现它很难制作。已经花了很多时间,但仍然没有运气如何解决这个问题。我正在使用 d3js 库

我有类似的东西

并想用渐变填充,就像这样

任何建议如何使它更接近它。也许你们中的某些人已经遇到过这个问题并且对此有所了解。

将不胜感激任何答案和建议。

【问题讨论】:

  • 我同意这不是微不足道的(除非事实证明有一个 SVG 内置方法可以做到这一点,我很确定没有)。即使在 Photoshop 中这样做也是一个挑战。我能想到的实现这种效果的唯一方法是将圆弧分成一堆较小的圆弧段,使用实心填充或方向角与圆弧切线角匹配的线性渐变。可行,但并非微不足道。
  • 您想要每个“切片”上的渐变或整个事物的渐变?
  • @Mark 是的,正好横跨整个馅饼,从一个切片到另一个切片平滑溢出,但它们之间有间隙。

标签: d3.js gradient pie-chart


【解决方案1】:

正如@meetamit 在他的评论中所说,我找不到像您展示的那样生成 圆形 渐变的内置 SVG 方法。但是,如果我们以这个出色的 answer 为基础,我们可以很好地复制您的图表。

诀窍是制作一个由 360 度弧组成的甜甜圈(每个度数一个)来自己创建渐变。然后我们可以使用pie 计算不包括我们的切片填充应该在的弧:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
  </head>

  <body>
    <script>
    
      // sample data
      var data = [10,20,30,40,50];
    
      var height = 500,
          width = 500,
          radius = 200,
          padding = 0.04;
      
      var svg = d3.select('body')
        .append('svg')
        .attr('width', width)
        .attr('height', height)
        .append('g')
        .attr('transform', 'translate(' + width/2 + ',' + width/2 + ')');
        
      var arc = d3.svg.arc()
        .innerRadius(radius - 100)
        .outerRadius(radius);
      
      // pie the data
      var pie = d3.layout.pie()
        .sort(null)
        .value(function(d) { return d; });
      data = pie(data);

      // create our gradient
      var colors = [],
          slice = 0,
          inPad = false;
      // 360 degrees
      d3.range(360).forEach(function(d, i) {
        // convert to radians
        var start = i * (Math.PI / 180),
            end = (i + 1) * (Math.PI / 180);
        // if we are in a padding area
        if ( Math.abs(data[slice].startAngle - start) < padding || 
            Math.abs(data[slice].endAngle - start) < padding ) {
          inPad = true;
        } else {
          // when to move to next slice
          if (inPad){
            // move to next slice
            slice++;
            // "stick" on last slice
            if (slice >= data.length) slice = 4;
          }
          inPad = false;
        }
        // only push if not in padding
        if (!inPad){
          colors.push({
            startAngle: start,
            endAngle: end,
            fill: d3.hsl(i, 1, .5).toString()
          });
        }
      });
      // add arcs
      svg.selectAll('.arc')
        .data(colors)
        .enter()
        .append('path')
        .attr('class', 'arc')
        .attr('d', arc)
        .style('fill', function(d){
          return d.fill;
        })
        .style('stroke',function(d){
          return d.fill;
        });
    </script>
  </body>

</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    相关资源
    最近更新 更多