This repository was archived by the owner on May 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathDonutChart.js
More file actions
100 lines (79 loc) · 2.45 KB
/
DonutChart.js
File metadata and controls
100 lines (79 loc) · 2.45 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
// @flow
import * as React from 'react';
import Legend from 'components/Legend';
import Chart from 'components/Chart';
import type { TransactionSummary } from 'selectors/transactions';
import { arc, pie, scaleOrdinal, schemeCategory10 } from 'd3';
import { shuffle } from 'utils/array';
import Path from './Path';
import styles from './styles.module.scss';
const randomScheme = shuffle(schemeCategory10);
type DonutChartProps = {
data: TransactionSummary[],
dataLabel: string,
dataKey: string,
dataValue?: string,
color?: Function,
height?: number,
innerRatio?: number,
};
class DonutChart extends React.Component<DonutChartProps> {
static defaultProps = {
color: scaleOrdinal(randomScheme),
height: 300,
innerRatio: 4,
dataValue: 'value',
};
componentWillMount() {
this.updateChartVariables();
}
componentWillReceiveProps(nextProps: DonutChartProps) {
const { data, color, height } = nextProps;
const old = this.props;
if (old.data !== data || old.color !== color || old.height !== height) {
this.updateChartVariables();
}
}
getPathArc = () => {
const { height, innerRatio } = this.props;
return arc()
.innerRadius(Number(height) / Number(innerRatio))
.outerRadius(Number(height) / 2);
};
chart: any;
pathArc: any;
colorFn: any;
outerRadius: number;
boxLength: number;
chartPadding = 8;
updateChartVariables = () => {
const { data, dataValue, color, height } = this.props;
this.chart = pie()
.value(d => d[dataValue])
.sort(null);
this.outerRadius = Number(height) / 2;
this.pathArc = this.getPathArc();
this.colorFn = color && color.domain && color.domain([0, data.length]);
this.boxLength = height + this.chartPadding * 2;
};
render() {
const { data, dataLabel, dataValue, dataKey } = this.props;
const { outerRadius, pathArc, colorFn, boxLength, chartPadding } = this;
return (
<div className={styles.donutChart}>
<Chart
width={boxLength}
height={boxLength}
padding={chartPadding}
transform={`translate(${outerRadius},${outerRadius})`}
>
{this.chart(data).map((datum, index) => (
<Path data={datum} index={index} fill={colorFn(index)} arcFn={pathArc} key={datum.data[dataKey]} />
))}
</Chart>
<Legend color={colorFn} {...{ data, dataValue, dataLabel, dataKey }} />
</div>
);
}
}
export default DonutChart;