tilly
tilly

Reputation: 2610

Recharts: have both outside and inside label on Pie chart

I am creating a pie chart with the help of the Recharts library. This Pie chart shows the distribution of various sources of income. Currently I only show a label on the outside of the name (img 1, code can be seen in linked code sandbox).

However, I would also like to have a percentage number in the center of every piece of the pie. (paint example of desired outcome at img 2). How would I achieve this with recharts?

Code sandbox example

As it is now

enter image description here

Upvotes: 0

Views: 4098

Answers (2)

Hassan Haroon
Hassan Haroon

Reputation: 34

Here is the code hope it helps. It's made with LabelList

<PieChart width={350} height={380}>
    <Pie
        dataKey="volume"
        isAnimationActive={true}
        data={currentPieValue()}
        outerRadius={80}
        fill="#08B8A1"
        label
        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
    >
        <LabelList dataKey="name" position="right" style={{ fontSize: "10px" }} />
        {currentPieValue().map((entry, index) => (
            <Cell key={`cell-${index}`} fill={colors[index]} />
        ))}
    </Pie>
    <Tooltip />
</PieChart>

Pie Chart

Upvotes: 1

Universo Frontend
Universo Frontend

Reputation: 111

I have found two possible solutions, both by adding the LabelList inside the Pie tag:

  1. Put the percentage directly of each one in the data and then in the dataKey of the LabelList refer to this percentage.
  2. Create an arrow function where to calculate the percentage in relation to the value and the total, which we will put as the second parameter, will calculate the percentage.
  • With the toFixed function we round to two decimals
  • With the replace function we exchange the point for the comma to display it.

In the css we add the following class to change the type and font size of the percentages:

.label-percentage {
   font-family: arial;
   font-size: 20px;
}

Code sandbox Solution

Result of the solution in photo enter image description here

Upvotes: 1

Related Questions