Search code examples
pythonmatplotlibpie-chart

Pie-chart in python


I am trying to make a pie chart with python but all the labels are overlapping. Is there any way to try to ensure that they are inside the pie chart but not overlapping?

Here's my code

import matplotlib.pyplot as plt

labels = ['Cropland', 'Forest', 'Cloud', 'Shadow', 'Water', 'Grassland', 'Bare ground']
sizes = [1737019, 105209472, 5210012, 4638330, 148082,1276550, 2340935]
colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink']
patches, texts = plt.pie(sizes, colors=colors, shadow=False, startangle=90)
plt.pie(sizes, labels=labels, autopct='%1.0f%%', pctdistance=1.4, labeldistance=1.8)
plt.legend(patches, labels, loc="lower left")
plt.axis('equal')
plt.tight_layout()
plt.savefig('LULC_20200425.png', bbox_inches='tight', dpi=600)
plt.show()

enter image description here


Solution

  • Reduce and rotate the labels.

    import matplotlib.pyplot as plt
    
    plt.figure(dpi=150)
    labels = ['Cropland', 'Forest', 'Cloud', 'Shadow', 'Water', 'Grassland', 'Bare ground']
    sizes = [1737019, 105209472, 5210012, 4638330, 148082,1276550, 2340935]
    
    colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink']
    
    patches, texts = plt.pie(sizes, colors=colors, shadow=False, startangle=90,textprops={'fontsize': 8})
    plt.pie(sizes, labels=labels, autopct='%1.0f%%', pctdistance=1.15, labeldistance=0.50,rotatelabels = True, textprops = dict(rotation_mode = 'anchor', va='center', ha='left', fontsize=8))
    
    plt.legend(patches, labels, loc="lower left")
    plt.axis('equal')
    plt.tight_layout()
    plt.show()
    

    enter image description here