Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14106

Remove labels but keep legend in a pie chart

How can I remove the labels from a pie chart but keep the legend ?

import matplotlib.pyplot as plt

x = [15, 30, 55]
labels = [1, 2, 3]

plt.figure(figsize=(3, 3), dpi=72)
plt.pie(x, labels=labels)
plt.legend()
plt.savefig('pie_1.png')

enter image description here

Upvotes: 13

Views: 8718

Answers (4)

hkohli
hkohli

Reputation: 21

A very simple way is to set the label distance to None, as suggested in the matlplotlib.pyplot.pie documentation.

This worked very well in my case.

import matplotlib.pyplot as plt

x = [15, 30, 55]
labels = [1, 2, 3]

plt.figure(figsize=(3, 3), dpi=72)
plt.pie(x, labels=labels, labeldistance=None)
plt.legend()
plt.savefig('pie_1.png')

Upvotes: 2

Diziet Asahi
Diziet Asahi

Reputation: 40727

As an alternative to IMCoins' answer, which is the best way to proceed, you could also keep your current code, but delete the labels from the pie chart.

x = [15, 30, 55]
labels = [1, 2, 3]

plt.figure(figsize=(3, 3), dpi=72)
patches, texts = plt.pie(x, labels=labels)
plt.legend()
for t in texts:
    t.remove()

Upvotes: 2

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339430

You can remove the labels argument from the pie and add it to the legend. Instead of

plt.pie(x,labels=labels)
plt.legend()

use

plt.pie(x)
plt.legend(labels=labels)

Complete example:

import matplotlib.pyplot as plt

x = [15, 30, 55]
labels = [1, 2, 3]

plt.figure(figsize=(3, 3), dpi=72)
plt.pie(x)
plt.legend(labels=labels)
plt.show()

enter image description here

Upvotes: 12

IMCoins
IMCoins

Reputation: 3306

If I were you, I'd create a custom legend, instead of letting matplotlib creating its own automatic one. You are now asking matplotlib to plot the labels using labels=labels in plt.pie().

import matplotlib.pyplot as plt

x = [15, 30, 55]
labels = [1, 2, 3]
colors = ['blue', 'red', 'grey']

plt.figure(figsize=(3, 3), dpi=72)
patches, texts = plt.pie(x, colors=colors)
plt.legend(patches, labels)
plt.show()
# plt.savefig('pie_1.png')

Imgur

Upvotes: 1

Related Questions