代码之家  ›  专栏  ›  技术社区  ›  Jane Wayne

用typescript+angular 7中的d3饼图设置文本标签位置和相关多段线时出现问题

  •  0
  • Jane Wayne  · 技术社区  · 7 年前

    我想做一个 d3 (版本5,版本5)饼图模型 this block/example 是的。然而,在许多d3示例中,作者使用 JavaScript 经常使用 this 内部匿名方法(在 TypeScript )中。我试着把这个例子改编成 TypeScript + Angular 7 没有成功。圆环图饼图切片的位置和绘制正确,但文本标签重叠,从文本到饼图切片的多段线不正确(它们可能按照代码正确呈现,但代码错误地指定了如何呈现这些线)。

    我的html代码很简单,只是有一个 svg 元素。

    <svg id="chart"></svg>
    

    我的typescript代码如下所示。

    export class AppComponent implements AfterViewInit {
      ngAfterViewInit() {
        const data = [
          { name: 'a', cost: 43.0 },
          { name: 'b', cost: 18.0 },
          { name: 'c', cost: 85.0 },
          { name: 'd', cost: 350.0 },
          { name: 'e', cost: 1000.0 },
          { name: 'f', cost: 830.0 },
          { name: 'g', cost: 200.0 },
          { name: 'h', cost: 60.0 }
        ];
    
        const svgWidth = 500;
        const svgHeight = 250;
        const radius = Math.min(svgWidth, svgHeight) / 2.0;
        const svg = d3.select('#chart')
          .attr('width', svgWidth)
          .attr('height', svgHeight)
          .append('g')
            .attr('transform', `translate(${svgWidth / 2.0}, ${svgHeight / 2.0})`);
    
        const color = d3.scaleOrdinal(d3.schemeCategory10);
        const pie = d3.pie()
          .value(d => d.cost)
          .sort(null);
    
        const arc = d3.arc()
          .innerRadius(radius * 0.6)
          .outerRadius(radius * 0.3);
        const arc2 = d3.arc()
          .innerRadius(radius * 0.9)
          .outerRadius(radius * 0.9);
    
        const path = svg.selectAll()
          .data(pie(data));
        path.enter().append('path')
          .attr('fill', (d, i) => color(i))
          .attr('d', arc)
          .attr('stroke', 'white')
          .attr('stroke-width', '6px');
    
        const midAngle = (item) => item.startAngle + (item.endAngle - item.startAngle) / 2.0;
    
        const text = svg.selectAll()
          .data(pie(data));
        text.enter().append('text')
          .attr('transform', d => {
            d.innerRadius = 0;
            d.outerRadius = radius;
            const centroid = arc2.centroid(d);
            centroid[0] = radius * (midAngle(d) < Math.PI ? 1 : -1);
            return `translate(${centroid})`;
          })
          .attr('dy', '.35em')
          .text(d => d.data.name);
    
        const polyline = svg.selectAll().data(pie(data));
        polyline.enter().append('polyline')
          .attr('points', d => {
            d.innerRadius = 0;
            d.outerRadius = radius;
            const centroid = arc2.centroid(d);
            centroid[0] = radius * (midAngle(d) < Math.PI ? 1 : -1);
            return [arc.centroid(d), arc2.centroid(d), centroid];
          });
      }
    }
    

    呈现的饼图如下所示。

    enter image description here

    还有,这里是闪电战的网址 app editor 参考文献。关于如何让这个例子起作用有什么想法吗?我不想或不需要动画的东西(在例子中引入复杂性)为我的目的。

    0 回复  |  直到 7 年前