forked from patternfly/patternfly-react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChartLegendInteractivePieChart.tsx
More file actions
94 lines (86 loc) · 2.64 KB
/
ChartLegendInteractivePieChart.tsx
File metadata and controls
94 lines (86 loc) · 2.64 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
import {
Chart,
ChartLegend,
ChartThemeColor,
ChartPie,
getInteractiveLegendEvents,
getInteractiveLegendItemStyles
} from '@patternfly/react-charts/victory';
export const ChartLegendInteractivePieChart: React.FunctionComponent = () => {
const [hiddenSeries, setHiddenSeries] = React.useState<Set<number>>(new Set());
const series = [
{
datapoints: { x: 'Cats', y: 35 },
legendItem: { name: 'Cats: 35' }
},
{
datapoints: { x: 'Dogs', y: 55 },
legendItem: { name: 'Dogs: 55' }
},
{
datapoints: { x: 'Birds', y: 10 },
legendItem: { name: 'Birds: 10' }
}
];
// Returns groups of chart names associated with each data series
const getChartNames = () => {
const result = [];
series.map((_, _index) => {
// Provide names for each series hidden / shown -- use the same name for a pie chart
result.push(['pie']);
});
return result;
};
// Returns legend data styled per hiddenSeries
const getLegendData = () =>
series.map((s, index) => ({
...s.legendItem, // name property
...getInteractiveLegendItemStyles(hiddenSeries.has(index)) // hidden styles
}));
// Hide each data series individually
const handleLegendClick = (props: { index: number }) => {
const newHiddenSeries = new Set(hiddenSeries);
if (newHiddenSeries.delete(props.index)) {
newHiddenSeries.add(props.index);
}
setHiddenSeries(newHiddenSeries);
};
// Returns true if data series is hidden
const isHidden = (index: number) => hiddenSeries.has(index);
// Returns onMouseOver, onMouseOut, and onClick events for the interactive legend
const getEvents = () =>
getInteractiveLegendEvents({
chartNames: getChartNames(),
isHidden,
legendName: 'chart6-ChartLegend',
onLegendClick: handleLegendClick
});
const data = [];
series.map((s, index) => {
data.push(!hiddenSeries.has(index) ? s.datapoints : { y: null });
});
return (
<div style={{ height: '275px', width: '300px' }}>
<Chart
ariaDesc="Average number of pets"
ariaTitle="Pie chart example"
events={getEvents()}
height={275}
legendComponent={<ChartLegend name={'chart6-ChartLegend'} data={getLegendData()} />}
legendPosition="bottom"
name="chart6"
padding={{
bottom: 65,
left: 20,
right: 20,
top: 20
}}
showAxis={false}
themeColor={ChartThemeColor.multiUnordered}
width={300}
>
<ChartPie constrainToVisibleArea data={data} labels={({ datum }) => `${datum.x}: ${datum.y}`} name="pie" />
</Chart>
</div>
);
};