首页 > 解决方案 > 离子“空白”页面中的d3js网络图

问题描述

我目前正在尝试实现代码; http://bl.ocks.org/jose187/4733747

在 Ionic/Angular 项目中。但是,我似乎无法使图形呈现。该项目基于“空白”模板。

我不断收到以下错误:“在'd3'中找不到导出'布局'(导入为'd3')

import { Component } from '@angular/core';

import * as d3 from 'd3'

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor() {
  }

  data = {
    nodes: [
      {name: 'node1', group: 1},
      {name: 'node2', group: 2},
      {name: 'node3', group: 2},
      {name: 'node4', group: 3}
    ],
    links: [
      {source: 2, target: 1, weight: 1},
      {source: 0, target: 2, weight: 3}
    ]
  };

  title = 'd3js Network Graph';
  width: 960;
  height: 500;
  margin = { top: 20, right: 20, bottom: 30, left: 40 };
  x: any;
  y: any;
  svg: any;
  g: any;
  link: any;
  node: any;
  simulation: any;

  ionViewDidEnter() {
    this.init();
    this.initForce();
    this.initLinks();
    this.initNodes();
    this.function();
  }

  init() {
    this.svg = d3.select('#graph')
      .append('svg')
      .attr('width', '100%')
      .attr('height', '100%');
  }

  initForce() {
    d3.layout.force()
      .gravity(.05)
      .distance(100)
      .charge(-100)
      .size([this.width, this.height]);
  }
  initLinks() {
    this.link = this.svg.selectAll('.link')
      .data(this.data.links)
      .enter().append('line')
      .attr('class', 'link')
      // tslint:disable-next-line:only-arrow-functions
      .style('stroke-width', function(d) { return Math.sqrt(d.weight); });

  }
  initNodes() {
    this.node = this.svg.selectAll('.node')
      .data(this.data.nodes)
      .enter().append('g')
      .attr('class', 'node')
      .append('cicle').attr('r', '5')
      // tslint:disable-next-line:only-arrow-functions
      .append().attr('dx', 12).attr('dy', '.35em').text(function(d) { return d.name; });
  }
  function() {
    this.link
      // tslint:disable-next-line:only-arrow-functions
      .attr('x1', function(d) { return d.source.x; })
      // tslint:disable-next-line:only-arrow-functions
      .attr('y1', function(d) { return d.source.y; })
      // tslint:disable-next-line:only-arrow-functions
      .attr('x2', function(d) { return d.target.x; })
      // tslint:disable-next-line:only-arrow-functions
      .attr('y2', function(d) { return d.target.y; });

    this.node
      // tslint:disable-next-line:only-arrow-functions
      .attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')'; });
  }
}

我觉得这与 d3js 版本的变化有关,但我不确定。任何人都可以帮忙吗?

标签: angularionic-frameworkd3.js

解决方案


您提到的错误确实表明您使用的是不同版本的 D3。您引用的示例使用的是 D3 v2,它比最新版本落后 4 个版本:) 您可以通过更改 D3 版本或更改代码以适合您的 D3 版本来解决此问题。

在您的项目中使用 D3v2

通过运行执行此操作:npm install --save d3@2

更新您的代码

您需要您的代码与您安装的任何版本的 D3 相匹配。这可能是 v6,因为在撰写本文时这是最新版本,但请转到D3 版本进行仔细检查。

如果您确实安装了 v6,您可以在使用最新版本的 D3 https://observablehq.com/@d3/force-directed-graph的 Observable 上查看这个示例。


推荐阅读