我正在尝试使用包含数字元素的一维数组制作基本折线图。

chart.html

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

graph.js
lineData = [10,15,20,25,30,35,40,35,30,25,20,15,10];
let svg = D3.select("#svg").attr('width', width).attr('height', height);

let chart = svg.append('g').classed('display', true).attr('transform', 'translate(' + this.padding.l + ', ' + this.padding.t + ')');

let x = D3.scaleLinear().domain([0, lineData.length]).range([0,width]);
let y = D3.scaleLinear().domain([0, D3.max(lineData)]).range([height, 0]);

let line = D3.line().x((d,i) => {return x(i);}).y((d) => {return y(d);}).curve();

chart.selectAll('.line').data([lineData]).enter().append('path').classed('line', true).attr('stroke', 'red').attr('d', (d) => {return line(d);});

我不断收到此错误:Error: <path> attribute d: Expected moveto path command ('M' or 'm'), "[object Object]".
----------更新(非简化的 Angular 组件)---------

条形曲线图.component.ts
import {Component, Input, OnInit, ViewChild} from '@angular/core';
import * as D3 from "d3";
import * as D3Tooltip from "d3-tip"

@Component({
  selector: 'app-bar-curve-chart',
  templateUrl: './bar-curve-chart.component.html',
  styleUrls: ['./bar-curve-chart.component.css']
})
export class BarCurveChartComponent implements OnInit {

  @ViewChild('svg') svg:any;

  private chart:any;
  private padding = {t:50, r:75, b:25, l:20};
  private x:any;
  private y:any;

  // Change Any to Data Type
  @Input('data') data:number[] = [5,10,15,20,25,30,35,30,25,20,15,10,5];
  @Input('lineData') lineData:any = [10,15,20,25,30,35,40,35,30,25,20,15,10];
  @Input('height') height:number = 700;
  @Input('width') width:number = 700;

  constructor() { }

  ngOnInit() {
    this.prep();
    this._plot();
  }

  private prep():void {
    let svg = D3.select(this.svg.nativeElement)
      .attr('width', this.width)
      .attr('height', this.height);

    this.chart = svg.append('g')
      .classed('display', true)
      .attr('transform', 'translate(' + this.padding.l + ', ' + this.padding.t + ')');

    this.x = D3.scaleLinear().domain([0, this.data.length]).range([0, this.width]);
    this.y = D3.scaleLinear().domain([0, D3.max(this.data)]).range([this.height, 0]);
  }

  private _plot():void {

    let line = D3.line()
      .x((d,i) => {return this.x(i);})
      .y((d) => {return this.y(d);}).curve();

    console.log(line(this.lineData));

    this.chart.selectAll('.line')
      .data([this.lineData])
      .enter()
        .append('path')
        .classed('line', true)
        .attr('stroke', 'red')
        .attr('d', (d) => {return line(d);});
  }

}

条形曲线图.component.html
<svg #svg ></svg>

最佳答案

您对线生成器的定义有误:

let line = D3.line()
  .x((d,i) => {return this.x(i);})
  .y((d) => {return this.y(d);}).curve();

如果不带参数使用 .curve() ,它会充当 getter:



因此,line 将保存对曲线工厂而不是线生成器的引用。如果您想要 curve factory 而不是默认的 d3.curveLinear ,则需要将其作为参数传递,或者您需要省略对 .curve() 的调用以获取行生成器。

顺便说一句:上述语句可以简化/美化为:
let line = D3.line()
  .x((d, i) => this.x(i))
  .y(this.y);

10-08 05:17