我正在使用d3制作一个与此处的示例非常相似的角度分量
https://bl.ocks.org/mbostock/ca5b03a33affa4160321
我没有收到图表未显示的任何错误。在示例链接代码中,他们使用一个csv文件,但我已将其转换为json文件。数据已正确导入,正在接收。
我是d3的新手,所以我确定这里缺少简单的东西。
打字稿(角度4)
import { Component, OnInit, ElementRef, ViewChild, AfterViewInit, HostListener } from '@angular/core';
import * as d3 from 'd3';
import * as moduleJson from './module-data.json';
@Component({
selector: 'app-module-explosion',
templateUrl: './module-explosion.component.html',
styleUrls: ['./module-explosion.component.scss']
})
export class ModuleExplosionComponent implements OnInit {
// Targets the container so we can get the height for D3
@ViewChild('exoGraph') exoGraph: ElementRef;
scWidth: number; // The width of the screen
h: number; // Container Height
w: number; // Container Width
flare: any;
constructor() {
this.scWidth = window.innerWidth;
this.flare = moduleJson;
}
ngOnInit() { }
ngAfterViewInit() {
this.h = 500;
this.w = this.exoGraph.nativeElement.clientWidth;
this.initGraph();
}
@HostListener('window:resize')
onResize() {
this.h = this.exoGraph.nativeElement.clientHeight;
this.w = this.exoGraph.nativeElement.clientWidth;
}
svg: any;
initGraph() {
// appends a 'group' element to 'svg'
this.svg = d3.select('#module-explosion-graph')
.append('svg')
.attr('width', this.w)
.attr('height', this.h);
const format = d3.format(',d');
const color = d3.scaleSequential(d3.interpolateMagma)
.domain([-4, 4]);
const stratify = d3.stratify()
.parentId(d => d.id.substring(0, d.id.lastIndexOf('.')));
const pack = d3.pack()
.size([this.w - 2, this.h - 2])
.padding(3);
const root = stratify(this.flare)
.sum(d => d.value)
.sort((a, b) => b.value - a.value);
pack(root);
const node = this.svg.select('g')
.selectAll('g')
.data(root.descendants())
.enter().append('g')
.attr('transform', d => `translate('${d.x}, ${d.y}')`)
.attr('class', d => 'node' + (!d.children ? ' node--leaf' : d.depth ? '' : 'node--root'))
.each(d => d.node = this)
.on('mouseover', hovered(true))
.on('mouseout', hovered(false));
node.append('circle')
.attr('id', d => 'node-' + d.id)
.attr('r', d => d.r)
.style('fill', d => color(d.depth));
const leaf = node.filter(d => !d.children);
leaf.append('clipPath')
.attr('id', d => 'clip-' + d.id)
.append('use')
.attr('xlink:href', d => '#node-' + d.id + '');
leaf.append('text')
.attr('clip-path', d => 'url(#clip-' + d.id + ')')
.selectAll('tspan')
.data(d => d.id.substring(d.id.lastIndexOf('.') + 1).split(/(?=[A-Z][^A-Z])/g))
.enter().append('tspan')
.attr('x', 0)
.attr('y', (d, i, nodes) => 13 + (i - nodes.length / 2 - 0.5) * 10)
.text(d => d);
node.append('title')
.text(d => d.id + '\n' + format(d.value));
function hovered(hover) {
return function(d) {
d3.selectAll(d.ancestors().map(d => d.node)).classed('node--hover', hover);
};
}
}
}