user1893649
user1893649

Reputation: 177

Moving PieChart label outside of circle - ReactJs / Rechart

I'm using Recharts and I can't figure out how to move the percentage labels of my pie chart outside of the pie chart:

enter image description here

Here is my PieChart code:

  <ResponsiveContainer width="100%" height={300}>
  <PieChart height={250}>
    <Pie
      data={this.props.data}
      cx="50%"
      cy="60%"
      outerRadius={100}
      fill="#8884d8"
      dataKey="value"
      label={({
        cx,
        cy,
        midAngle,
        innerRadius,
        outerRadius,
        percent,
        index
      }) => {
        const RADIAN = Math.PI / 180;
        // eslint-disable-next-line
        const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
        // eslint-disable-next-line
        const x = cx + radius * Math.cos(-midAngle * RADIAN);
        // eslint-disable-next-line
        const y = cy + radius * Math.sin(-midAngle * RADIAN);

        return (
          <text
            x={x}
            y={y}
            fill="#000000"
            textAnchor={x > cx ? "start" : "end"}
            dominantBaseline="hanging"
          >
            {this.props.data[index].name} ({`${(percent * 100).toFixed(0)}%`})
          </text>
        );
      }}
      onClick={this.props.handleClick}
    >
      {
        this.props.data.map((entry, index) => <Cell key={`cell-${index}`} fill={chartColors[index % chartColors.length]} />)
      }
    </Pie>
  </PieChart>
</ResponsiveContainer>

I'm assuming the textAnchor and dominantBaseline properties need to be tinkered with, but I'm unfamiliar with how to use them. Can someone point me in the right direction? Thanks!

Upvotes: 1

Views: 2421

Answers (1)

meghan
meghan

Reputation: 21

I was trying to figure this out myself and found a solution... you need to change the 0.5

const radius = innerRadius + (outerRadius - innerRadius) * 0.5;

I changed mine to

const radius = innerRadius + (outerRadius - innerRadius) * 1.4;

Upvotes: 2

Related Questions