Is it possible to avoid labels overlapping in Pie recharts js?

Viewed 161

I used the Pie component from Recharts js and the problem is that I get labels overlapping for labels with the same value. here is some of my code:
<PieChart>
       <Pie dataKey="value"
       data={data}
       fill="#536A6D"
       label nameKey="name"
       >
      <LabelList dataKey="name" position="insideStart" />
      <Pie>
</PieChart>

Is it possible to arrange the labels so that they do not collide with each other?
Thank you in advance!

1 Answers

Yes, you will have to conditionally render the labelline and label attribute. In my case only the zero values overlap so when the value is zero I do not render the value. Other examples online will help with the custom label but there is nothing over the little label line left over, I had this problem and had to dig through the source code to come up with the custom code /:

<Pie
 data={dataZ}
 cx={150 + wid - pad / 2}
 cy={150}
 innerRadius={70 + scaler}
 outerRadius={100 + scaler}
 fill="#8884d8"
 paddingAngle={1}
 dataKey="value"
 label={RenderLabel2}
 labelLine={RenderCustomizedLabelLine}
>




let RenderCustomizedLabelLine = function (props: any) {
    return (props.value != 0 ? <path stroke={props.stroke} d={`M${props.points[0].x},${props.points[0].y}L${props.points[1].x},${props.points[1].y}`} className="customized-label-line" /> : <polyline stroke={props.stroke} fill="none" />)    
  }

let RenderLabel2 = function (props: any) {
    const RADIAN = Math.PI / 180;
    const radius = 25 + props.innerRadius + (props.outerRadius - props.innerRadius);
    const x = props.cx + radius * Math.cos(-props.midAngle * RADIAN);
    const y = props.cy + radius * Math.sin(-props.midAngle * RADIAN);


    return (props.value != 0 ? <text
        className="recharts-text recharts-pie-label-text"
        x={x}
        y={y}
        fontSize='16'
        fontFamily='sans-serif'
        dominantBaseline="central"
        cy={props.cy}
        cx={props.cx}
        fill="#666"
        textAnchor={props.x > props.cx ? 'start' : 'end'}
    >{Number.isInteger(props.value) ? Number(props.value) : Number(props.value).toFixed(1)}%</text> : <g>
    <text x={500} y={y} fill="#transparent" rotate="90"></text>
   </g>)

}

Related