-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackTotalLabels.tsx
More file actions
71 lines (64 loc) · 1.9 KB
/
Copy pathStackTotalLabels.tsx
File metadata and controls
71 lines (64 loc) · 1.9 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
import * as React from 'react';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { BarPlot } from '@mui/x-charts/BarChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { useBarSeries, useXScale, useYScale } from '@mui/x-charts/hooks';
import { styled } from '@mui/material/styles';
export default function StackTotalLabels() {
return (
<ChartsContainer
xAxis={[{ scaleType: 'band', data: ['Q1', 'Q2', 'Q3'] }]}
series={[
{
type: 'bar',
id: 'a',
stack: 'total',
data: [5, 17, 11],
barLabel: 'value',
},
{ type: 'bar', id: 'b', stack: 'total', data: [4, 8, 6], barLabel: 'value' },
]}
height={400}
yAxis={[{ width: 30 }]}
margin={{ left: 0, right: 10, top: 30 }}
>
<BarPlot />
<StackTotals />
<ChartsXAxis />
<ChartsYAxis />
</ChartsContainer>
);
}
function StackTotals() {
const xScale = useXScale<'band'>();
const yScale = useYScale();
const barSeries = useBarSeries();
const categories = xScale.domain();
const bandWidth = xScale.bandwidth();
return (
<React.Fragment>
{categories.map((category, dataIndex) => {
const total = barSeries.reduce(
(acc, series) =>
acc + (series.stack === 'total' ? (series.data[dataIndex] ?? 0) : 0),
0,
);
const cx = (xScale(category) ?? 0) + bandWidth / 2;
const cy = yScale(total) ?? 0;
return (
<TotalLabel key={String(category)} x={cx} y={cy - 8}>
{total}
</TotalLabel>
);
})}
</React.Fragment>
);
}
const TotalLabel = styled('text')(({ theme }) => ({
...theme?.typography?.body2,
fontWeight: 600,
stroke: 'none',
fill: (theme.vars || theme)?.palette?.text?.primary,
dominantBaseline: 'central',
}));