繁体   English   中英

使用 d3.js 和 TypeScript 绘制饼图时出现编译错误

[英]Compilation errors when drawing a piechart using d3.js and TypeScript

我正在尝试使用 d3.js 库和 TypeScript 绘制饼图。 我有以下代码:

"use strict";
module Chart {
  export class chart {

    private chart: d3.Selection<string>;
    private width: number;
    private height: number;
    private radius: number;
    private donutWidth: number;
    private dataset: { label: string, count: number }[];
    private color: d3.scale.Ordinal<string, string>;

    constructor(container: any) {
      this.width = 360;
      this.height = 360;
      this.radius = Math.min(this.width, this.height) / 2;
      this.donutWidth = 75;

      this.dataset = [
        { label: 'Road', count: 5500 },
        { label: 'Bridge', count: 8800 },
        { label: 'Tunnel', count: 225 },
      ];

      this.color = d3.scale.category10();

      this.init(container);

    }

    private init(container) {
      this.chart = d3.select(container).append('svg')
        .attr('width', this.width)
        .attr('height', this.height)
        .append('g')
        .attr('transform', 'translate(' + (this.width / 2) +
        ',' + (this.height / 2) + ')');
    }

    draw() {

      var arc = d3.svg.arc()
        .innerRadius(this.radius - this.donutWidth)  // NEW
        .outerRadius(this.radius);

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

      var path = this.chart.selectAll('path')
        .data(pie(this.dataset.map(function(n) {
          return n.count;
        })))
        .enter()
        .append('path')
        .attr('d', arc)
        .attr('fill', function(d, i) {
          return Math.random();
        });
    }

  }
}

代码未编译并出现错误:

 Argument of type 'Arc<Arc>' is not assignable to parameter of type '(datum: Arc<number>, index: number, outerIndex: number) => string | number | boolean'.
>>   Types of parameters 'd' and 'datum' are incompatible.
>>     Type 'Arc' is not assignable to type 'Arc<number>'.
>>       Property 'value' is missing in type 'Arc'.   

当我尝试将d属性添加到我的 svg 上的每个path元素时,会出现编译错误:

var path = this.chart.selectAll('path')
        .data(pie(this.dataset.map(function(n) {
          return n.count;
        })))
        .enter()
        .append('path')
        .attr('d', arc)
        .attr('fill', function(d, i) {
          return Math.random();
        });

根据文档,弧“既是对象又是函数”。 我看到我可以通过调用arc(datum[, index])来访问它,例如通过硬编码arc[0] 当我这样做时,我的编译错误消失了,但 svg 中每个path元素的d属性都丢失了,我最终得到了一个 svg,如:

    <svg height="360" width="360">
      <g transform="translate(180,180)">
         <path fill="0.35327279710072423"></path>
         <path fill="0.6333000506884181"></path>
         <path fill="0.9358429045830001"></path>
      </g>
    </svg>

我已经将代码作为纯 JavaScript 运行,没有任何问题。

尝试更换

.attr('d', arc)   

.attr('d', <any>arc)  

这在我的计算机上隐藏了编译器错误,但如果它真的有效......好吧,我不知道。

我对这个问题的理解是,你提供.data与功能的number值和打字稿编译器预计.attr也包含了号码,但您提供的arc代替。

来到这里是因为我在使用 D3 v5 时遇到了同样的问题!

解决方案:使用PieArcDatum接口(在我看来很奇怪的名字!!!)

细节:

import { PieArcDatum } from 'd3-shape';

... 

type Population = { time: string, population: number; };

...

const svg = element.append("g")
    .attr("transform", `translate(${300}, ${160})`)
;

const pie = d3.pie<Population>()
    .sort(null)
    .value((record) => record.population);

const path = d3.arc<PieArcDatum<Population>>()
    .innerRadius(0)
    .outerRadius(150)
;

// Beim selectAll kommt eine leere Selection zurück da es noch keinen Circle gibt
const data = pie(worldPopulation);
const arch = svg.selectAll(".arc")
    .data(data)
    .enter()
    .append("g")
        .attr("class", "arc")
;

arch.append('path')
    .attr("d", path)
;


旁注:我正在使用 WebStorm,WS 无法找到(自动导入)PieArcDatum - 我必须手动导入它...

虽然使用<any>可以避免编译错误,但它首先违背了进行类型检查的目的。 对 Arc 布局的d3.d.ts定义进行多次反复试验和质量时间之后,我想出了如何使类型d3.d.ts

function draw() {

    let arc = d3.svg.arc<d3.layout.pie.Arc<number>>()
        .innerRadius(this.radius - this.donutWidth)
        .outerRadius(this.radius);

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

    let tfx = (d: d3.layout.pie.Arc<number>): string => `translate(${arc.centroid(d)})`);

    // create a group for the pie chart
    let g = this.chart.selectAll('g')
        .data(pie(this.dataset.map(n => n.count)))
        .enter().append('g');

    // add pie sections
    g.append('path').attr('d', arc);

    // add labels
    g.append('text').attr('transform', tfx).text(d => d.data.label);
}

除了原始问题之外,我还展示了如何向饼图添加标签并保持 Typescript 的强类型化。 请注意,此实现利用了备用构造函数d3.svg.arc<T>(): Arc<T> ,它允许您为arc段指定类型。

更新

上面的代码假设传递的data是一个数字数组。 如果您查看代码(特别是访问器n => n.countd => d.data.label ),显然不是。 这些访问器也有一个隐式的any类型,即(n: any) => n.count 如果n恰好是一个没有count属性的对象,这可能会引发运行时错误。 这是一个重写,使data的形状更加明确:

interface Datum {
    label: string;
    count: number;
}

function draw() {

    // specify Datum as shape of data
    let arc = d3.svg.arc<d3.layout.pie.Arc<Datum>>()
        .innerRadius(this.radius - this.donutWidth)
        .outerRadius(this.radius);

    // notice accessor receives d of type Datum
    let pie = d3.layout.pie<Datum>().sort(null).value((d: Datum):number => d.count);

    // note input to all .attr() and .text() functions
    // will be of type d3.layout.pie.Arc<Datum>
    let tfx  = (d: d3.layout.pie.Arc<Datum>): string => `translate(${arc.centroid(d)})`;
    let text = (d: d3.layout.pie.Arc<Datum>): string => d.data.category;

    // create a group for the pie chart
    let g = this.chart.selectAll('g')
        .data(pie(data))
        .enter().append('g');

    // add pie sections
    g.append('path').attr('d', arc);

    // add labels
    g.append('text').attr('transform', tfx).text(text);
}

在第二个版本中,不再有任何隐式的any类型。 另一件需要注意的事情是接口的名称Datum是任意的。 您可以随意命名该接口,但必须小心地将所有对Datum引用更改为您选择的任何更合适的名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM