import { Component, OnInit, Input, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import * as d3 from 'd3';
@Component({
selector: 'app-horizontal-group-bar-chart',
templateUrl: './horizontal-group-bar-chart.component.html',
styleUrls: ['./horizontal-group-bar-chart.component.css']
})
export class HorizontalGroupBarChartComponent implements OnInit, AfterViewInit {
@Input() data: any[] = [];
@ViewChild('chart', { static: true }) private chartContainer: ElementRef;
private margin = { top: 20, right: 20, bottom: 30, left: 40 };
private width = 600 - this.margin.left - this.margin.right;
private height = 400 - this.margin.top - this.margin.bottom;
ngOnInit(): void {
}
ngAfterViewInit(): void {
this.createChart();
}
private createChart() {
const svg = d3
.select(this.chartContainer.nativeElement)
.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})`);
const x0 = d3.scaleBand({
domain: this.data.map(d => d.category),
range: [0, this.width],
paddingInner: 0.1,
});
const x1 = d3.scaleBand({
domain: ['Group 1', 'Group 2', 'Group 3'],
range: [0, x0.bandwidth()],
padding: 0.05,
});
const y = d3.scaleLinear({
domain: [0, d3.max(this.data, d => d3.max(d.groups, group => group.value))],
range: [this.height, 0],
nice: true,
});
const color = d3.scaleOrdinal(d3.schemeCategory10);
svg
.append('g')
.selectAll('g')
.data(this.data)
.enter()
.append('g')
.attr('transform', d => `translate(${x0(d.category)}, 0)`)
.selectAll('rect')
.data(d => d.groups)
.enter()
.append('rect')
.attr('x', d => x1(d.group))
.attr('y', d => y(d.value))
.attr('width', x1.bandwidth())
.attr('height', d => this.height - y(d.value))
.attr('fill', d => color(d.group));
svg
.append('g')
.attr('transform', `translate(0, ${this.height})`)
.call(d3.axisBottom(x0));
svg.append('g').call(d3.axisLeft(y));
}
}
typescript Copy code
chartData = [
{
category: 'Category 1',
groups: [
{ group: 'Group 1', value: 20 },
{ group: 'Group 2', value: 30 },
{ group: 'Group 3', value: 15 },
],
},
{
category: 'Category 2',
groups: [
{ group: 'Group 1', value: 10 },
{ group: 'Group 2', value: 25 },
{ group: 'Group 3', value: 35 },
],
},
// Add more categories as needed
];