import { Component, OnInit } from '@angular/core';
import * as d3 from 'd3';
interface Series {
name: string;
values: number[];
}
@Component({
selector: 'app-bar-chart',
templateUrl: './bar-chart.component.html',
styleUrls: ['./bar-chart.component.css']
})
export class BarChartComponent implements OnInit {
private margin = { top: 20, right: 20, bottom: 30, left: 40 };
private width: number;
private height: number;
private x: any;
private y: any;
private svg: any;
private xAxis: any;
private yAxis: any;
data: Series[] = [
{ name: 'Series 1', values: [20, 30, 10, 40, 30] },
{ name: 'Series 2', values: [50, 20, 40, 50, 30] },
{ name: 'Series 3', values: [30, 20, 50, 40, 60] }
];
ngOnInit() {
this.initSVG();
this.drawXAxis();
this.drawYAxis();
this.drawBars();
}
private initSVG() {
this.width = parseInt(d3.select('#bar-chart').style('width'), 10) - this.margin.left - this.margin.right;
this.height = 400 - this.margin.top - this.margin.bottom;
this.svg = d3
.select('#bar-chart')
.append('svg')
.attr('width', this.width + this.margin.left + this.margin.right)
.attr('height', this.height + this.margin.top + this.margin.bottom)
.append('g')
.attr('transform', `translate(${this.margin.left}, ${this.margin.top})`);
}
private drawXAxis() {
this.x = d3.scaleBand()
.range([0, this.width])
.domain(this.data.map((d, i) => i))
.padding(0.2);
this.svg.append('g')
.attr('transform', `translate(0, ${this.height})`)
.call(d3.axisBottom(this.x));
}
private drawYAxis() {
this.y = d3.scaleLinear()
.range([this.height, 0])
.domain([0, d3.max(this.data.map(d => d3.max(d.values)))]);
this.svg.append('g').call(d3.axisLeft(this.y));
}
private drawBars() {
this.svg.selectAll('.bar')
.data(this.data)
.enter().append('rect')
.attr('class', 'bar')
.attr('x', d => this.x(d.name))
.attr('y', d => this.y(d3.max(d.values)))
.attr('width', this.x.bandwidth())
.attr('height', d => this.height - this.y(d3.max(d.values)));
}
}
Now you should have a horizontal group bar chart using D3.js in your Angular application. You can customize the data, axis labels, and styling as needed.