Last active
February 3, 2019 16:32
-
-
Save AvocadoVenom/102dcd227e71dda5be17a54df0a97af2 to your computer and use it in GitHub Desktop.
d3 pie chart angular component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit, ViewEncapsulation } from '@angular/core'; | |
import { Item, DataService } from '../data.service'; | |
import * as d3 from 'd3'; | |
@Component({ | |
selector: 'app-pie-chart', | |
template: `<div id="pie"><svg></svg></div>`, | |
encapsulation: ViewEncapsulation.None | |
}) | |
export class PieChartComponent implements OnInit { | |
get height(): number { return parseInt(d3.select('body').style('height'), 10); } | |
get width(): number { return parseInt(d3.select('body').style('width'), 10); } | |
radius: number; | |
// Arcs & pie | |
private arc: any; private pie: any; private slices: any; | |
private color: any; | |
// Drawing containers | |
private svg: any; private mainContainer: any; | |
// Data | |
dataSource: Item[]; | |
constructor(private service: DataService) { | |
this.dataSource = this.service.getData(); | |
} | |
ngOnInit() { | |
this.svg = d3.select('#pie').select('svg'); | |
this.setSVGDimensions(); | |
this.color = d3.scaleOrdinal(d3.schemeCategory10); | |
this.mainContainer = this.svg.append('g').attr('transform', `translate(${this.radius},${this.radius})); | |
this.pie = d3.pie().sort(null).value((d: any) => d.abs); | |
this.draw(); | |
} | |
private setSVGDimensions() { | |
this.radius = (Math.min(this.width, this.height)) / 2; | |
this.svg.attr('width', 2 * this.radius).attr('height', 2 * this.radius); | |
this.svg.select('g').attr('transform', 'translate(' + this.radius + ',' + this.radius + ')'); | |
} | |
private draw() { | |
this.setArcs(); | |
this.drawSlices(); | |
} | |
private setArcs() { | |
this.arc = d3.arc().outerRadius(this.radius).innerRadius(this.radius * .75); | |
} | |
private drawSlices() { | |
this.slices = this.mainContainer.selectAll('path') | |
.remove().exit() | |
.data(this.pie(this.dataSource)) | |
.enter().append('g').append('path') | |
.attr('d', this.arc); | |
this.slices | |
.attr('fill', (d, i) => this.color(i)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment