-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBarChart.tsx
More file actions
116 lines (105 loc) · 3.4 KB
/
Copy pathBarChart.tsx
File metadata and controls
116 lines (105 loc) · 3.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import React, { useRef } from "react";
import { Bar } from "react-chartjs-2";
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend } from "chart.js";
import zoomPlugin from "chartjs-plugin-zoom";
import { getDistributedColor, createBarPattern } from "@/functions/Colors";
import { ChartDataSet } from "@/dto/ChartData";
import { Button } from "@equinor/eds-core-react";
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, zoomPlugin);
export interface BarChartProps {
graphData: ChartDataSet[];
aspectRatio?: number;
xLabel?: string;
yLabel?: string;
}
const BarChart: React.FC<BarChartProps> = ({ graphData, aspectRatio = 4, xLabel, yLabel }) => {
const chartRef = useRef<any>(null);
const allX = Array.from(new Set(graphData.flatMap((ds) => ds.data.map((point) => point.x))));
const hasStacking = graphData.some((ds) => ds.stack);
const datasets = graphData.map((ds, idx) => ({
label: ds.label,
hidden: ds.hidden || false,
data: allX.map((x) => {
const found = ds.data.find((point) => point.x === x);
return found ? found.y : null;
}),
backgroundColor: ds.pattern
? createBarPattern(ds.color ?? getDistributedColor(idx, graphData.length), ds.pattern)
: (ds.color ?? getDistributedColor(idx, graphData.length)),
...(ds.stack ? { stack: ds.stack } : {}),
}));
const chartData = {
labels: allX,
datasets,
};
const options = {
responsive: true,
aspectRatio,
datasets: {
bar: {
barPercentage: 0.7,
categoryPercentage: 0.8,
maxBarThickness: 40,
},
},
plugins: {
legend: {
position: "right" as const,
align: "start" as const,
labels: {
boxWidth: 12,
padding: 6,
font: { size: 11 },
},
maxWidth: 400,
},
zoom: {
pan: {
enabled: false,
mode: "xy" as const,
},
zoom: {
drag: {
enabled: true,
},
mode: "y" as const,
},
},
},
scales: {
x: {
grid: { display: true },
title: { display: !!xLabel, text: xLabel ?? "" },
},
y: {
grid: { display: true },
title: { display: !!yLabel, text: yLabel ?? "" },
stacked: hasStacking,
},
},
};
const handleResetZoom = () => {
if (chartRef.current) {
chartRef.current.resetZoom();
}
};
return (
<div>
<Bar ref={chartRef} data={chartData} options={options} />
<Button
variant="outlined"
onClick={handleResetZoom}
style={{
marginBottom: "12px",
marginTop: "12px",
height: "24px",
padding: "2px 8px",
fontSize: "0.85rem",
}}
>
Reset zoom
</Button>
</div>
);
};
export default BarChart;