Home > database >  Place labels within slices on matplotlib pie chart
Place labels within slices on matplotlib pie chart

Time:12-20

I'm looking to make a pie graph where the labels appear auto-rotated inside of the slices rather than outside.

enter image description here

I'm not sure how to do this or if I somehow need to force-feed them into autopct and then figure out a way to auto-rotate that?

It's not exactly complex, but below is my current python code:

import matplotlib.pyplot as plt

entity_names = ['The Desolation', 'The Corruption', 'The Eye', 'The Web', 'The Stranger', 'The Extinction', 'The Lonely', 'The Vast', 'The End', 'The Hunt', 'The Dark', 'The Buried', 'The Flesh', 'The Slaughter', 'The Spiral']
slice_sizes = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

plt.pie(slice_sizes, labels=entity_names, rotatelabels=True)

plt.savefig('pie_chart.svg')

CodePudding user response:

You could mirror the horizontal and vertical alignment of the generated texts. Setting labeldistance=0.95 puts the starting point just inside the wedges.

import matplotlib.pyplot as plt

entity_names = ['The Desolation', 'The Corruption', 'The Eye', 'The Web', 'The Stranger', 'The Extinction', 'The Lonely', 'The Vast', 'The End', 'The Hunt', 'The Dark', 'The Buried', 'The Flesh', 'The Slaughter', 'The Spiral']
slice_sizes = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

_, texts = plt.pie(slice_sizes, labels=entity_names, rotatelabels=True, labeldistance=0.95)
for t in texts:
    t.set_ha('right' if t.get_ha() == 'left' else 'left')
    t.set_va('top' if t.get_va() == 'bottom' else 'bottom')
plt.show()

matplotlib pie rotated labels inside

  • Related