The One
The One

Reputation: 93

Change position of label of Matplotlib pie chart

I have a simple pie chart with the percentage and label of each slice indicated. The percentage marks and labels are right in the middle of each of the pie slices, but I want these two to be moved to to a different part of the slice as indicated in the figure below, such that all labels are on the left side of the figure.

Is there a way to do this?

import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 12})

labels = 'A', 'B', 'C'
sizes = [5, 20, 75]
explode = (0.1, 0, 0)

fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90)
ax1.axis('equal')
plt.tight_layout()
plt.savefig('test.png')
plt.show()

enter image description here

Upvotes: 0

Views: 2148

Answers (1)

eh329
eh329

Reputation: 104

It is actually easy. Follow these steps:

1 - Drop label parameter from ax1.pie. Let it be just: ax1.pie(sizes, explode=explode autopct='%1.1f%%', shadow=True, startangle=90)

2 - Add plt.legend() after ax1.axis("equal") line.

3 - Pass your labels as an argument to plt.legend() i.e. plt.legend(labels).

4 - If you are still not happy with the location of the legend, there is one more parameter you can manipulate which is bbox_to_anchor.

5 - Pass bbox_to_anchor as the second parameter to plt.legend() and give it two numbers in form of tuple like: bbox_to_anchor = (2, 3). Play around with it until it is where you want it to be.

Upvotes: 1

Related Questions