A pie chart that has customized label
by Amir Danish
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/react-with-addons.min.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/react-dom.min.js"></script>
<script src="https://npmcdn.com/prop-types/prop-types.min.js"></script>
<script src="https://npmcdn.com/recharts/umd/Recharts.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
CSS
body {
margin: 0;
}
#container {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
width: 800px;
height: 800px;
background-color: #fff;
}
Babel + JSX
const { PieChart, Pie, Sector, Cell } = Recharts;
const data = [{name: 'Group A', value: 400}, {name: 'Group B', value: 300}];
const COLORS = ['#0088FE', '#00C49F'];
const RADIAN = Math.PI / 180;
const renderCustomizedLabel = ({ cx, cy, midAngle, innerRadius, outerRadius, percent, index }) => {
const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
const x = cx + radius * Math.cos(-midAngle * RADIAN);
const y = cy + radius * Math.sin(-midAngle * RADIAN);
return (
<text x={x} y={y} fill="white" textAnchor={x > cx ? 'start' : 'end'} dominantBaseline="central">
{`${(percent * 100).toFixed(0)}%`}
</text>
);
};
const SimplePieChart = React.createClass({
render () {
return (
<PieChart width={800} height={400} onMouseEnter={this.onPieEnter}>
<Pie
data={data}
cx={300}
cy={200}
labelLine={false}
label={renderCustomizedLabel}
outerRadius={80}
fill="#8884d8"
>
{
data.map((entry, index) => <Cell fill={COLORS[index % COLORS.length]}/>)
}
</Pie>
</PieChart>
);
}
})
ReactDOM.render(
<SimplePieChart />,
document.getElementById('container')
);