I need help making a bar chart using d3 and Angular(in VSCode). The x-axis doesn't seem to work properly. Can anyone assist me with this issue? Currently, only the y-axis is displaying without any additional response. I've been stuck on this problem for a while now and despite trying different code tweaks, there hasn't been any progress.
Thank you!
//elect.tsv enter image description here
//template.component.ts
import {Component, ElementRef, OnInit, ViewChild, AfterViewInit} from '@angular/core';
import * as d3 from 'd3';
interface ILayoutInfo {
marginTop: number;
marginRight: number;
marginBottom: number;
marginLeft: number;
height: number;
width: number;
boundedHeight?: number;
boundedWidth?: number;
}
interface IData {
idx : string;
elect : string;
fre : number;
decrease : number;
increase : number;
nochange : number;
}
@Component({
selector: 'app-template',
templateUrl: './template.component.html',
styleUrls: ['./template.component.scss']
})
export class TemplateComponent implements OnInit, AfterViewInit {
layout: ILayoutInfo;
@ViewChild('rootSvg') svgRoot!: ElementRef;
constructor() {
this.layout = {
marginTop: 20, marginRight: 20, marginBottom: 30, marginLeft: 40,
height: 500, width: 960
};
}
ngOnInit(): void {
}
ngAfterViewInit() {
d3.tsv('./assets/elect.tsv').then((d: any) => {
d.decrease = +d.decrease;
d.idx = +d.idx;
return d;
}).then((data: IData[]) => {
this.render(data);
});
}
render(data: IData[]): void {
const svg = d3.select(this.svgRoot.nativeElement)
.attr('width', this.layout.width)
.attr('height', this.layout.height);
const width = +svg.attr('width') - this.layout.marginLeft - this.layout.marginRight,
height = +svg.attr('height') - this.layout.marginTop - this.layout.marginBottom;
const x = d3.scaleBand().rangeRound([0, width]).padding(0.1);
const y = d3.scaleLinear().rangeRound([height, 0]);
console.log(x);
const g = svg.append('g')
.attr('transform', 'translate(' + this.layout.marginLeft + ',' + this.layout.marginTop + ')');
x.domain(data.map(d => d.idx));
y.domain([0, d3.max(data, (d: IData) => d.decrease) as number]);
g.append('g')
.attr('class', 'axis axis--x')
.attr('transform', 'translate(0,' + height + ')')
.call(d3.axisBottom(x).ticks(10))
.select('path')
.style('display', 'none');
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('Decrease');
g.selectAll('bar')
.data(data)
.enter().append('rect')
.attr('class', 'bar')
.attr('x', (d: IData) => x(d.idx) as number)
.attr('y', (d: IData) => y(d.decrease))
.attr('width', x.bandwidth())
.attr('height', function(d) { return height - y(d.decrease); })
.attr('fill', 'steelblue')
.on('mouseover', function (this) {
d3.select(this).attr('fill', 'brown');
})
.on('mouseout', function (this) {
d3.select(this).attr('fill', 'steelblue');
});
}
}
//template.component.html
<div class="container">
<svg #rootSvg class="chart"></svg>
</div>