Last active
August 2, 2019 12:23
-
-
Save jplemieux66/976e5dc2837a921b084cbab3b2e09e08 to your computer and use it in GitHub Desktop.
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, ElementRef, Input, OnChanges, ViewChild, ViewEncapsulation } from '@angular/core'; | |
import * as d3 from 'd3'; | |
import { DataModel } from 'src/app/data/data.model'; | |
@Component({ | |
selector: 'app-bar-chart', | |
encapsulation: ViewEncapsulation.None, | |
templateUrl: './bar-chart.component.html', | |
styleUrls: ['./bar-chart.component.scss'] | |
}) | |
export class BarChartComponent implements OnChanges { | |
@ViewChild('chart') | |
private chartContainer: ElementRef; | |
@Input() | |
data: DataModel[]; | |
margin = {top: 20, right: 20, bottom: 30, left: 40}; | |
constructor() { } | |
ngOnChanges(): void { | |
if (!this.data) { return; } | |
this.createChart(); | |
} | |
private createChart(): void { | |
d3.select('svg').remove(); | |
const element = this.chartContainer.nativeElement; | |
const data = this.data; | |
const svg = d3.select(element).append('svg') | |
.attr('width', element.offsetWidth) | |
.attr('height', element.offsetHeight); | |
const contentWidth = element.offsetWidth - this.margin.left - this.margin.right; | |
const contentHeight = element.offsetHeight - this.margin.top - this.margin.bottom; | |
const x = d3 | |
.scaleBand() | |
.rangeRound([0, contentWidth]) | |
.padding(0.1) | |
.domain(data.map(d => d.letter)); | |
const y = d3 | |
.scaleLinear() | |
.rangeRound([contentHeight, 0]) | |
.domain([0, d3.max(data, d => d.frequency)]); | |
const g = svg.append('g') | |
.attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')'); | |
g.append('g') | |
.attr('class', 'axis axis--x') | |
.attr('transform', 'translate(0,' + contentHeight + ')') | |
.call(d3.axisBottom(x)); | |
g.append('g') | |
.attr('class', 'axis axis--y') | |
.call(d3.axisLeft(y).ticks(10, '%')) | |
.append('text') | |
.attr('transform', 'rotate(-90)') | |
.attr('y', 6) | |
.attr('dy', '0.71em') | |
.attr('text-anchor', 'end') | |
.text('Frequency'); | |
g.selectAll('.bar') | |
.data(data) | |
.enter().append('rect') | |
.attr('class', 'bar') | |
.attr('x', d => x(d.letter)) | |
.attr('y', d => y(d.frequency)) | |
.attr('width', x.bandwidth()) | |
.attr('height', d => contentHeight - y(d.frequency)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I got problem while implementing above code you can see error in the above image