How to avoid overlapping of labels & autopct in a matplotlib pie chart?

前端 未结 2 1886
我在风中等你
我在风中等你 2020-12-13 20:11

My Python code is:

values = [234, 64, 54,10, 0, 1, 0, 9, 2, 1, 7, 7]
months = [\'Jan\', \'Feb\', \'Mar\', \'Apr\', \'May\', \'Jun\',
          \'Jul\',\'Aug\         


        
相关标签:
2条回答
  • 2020-12-13 20:22

    Alternatively you can put the legends beside the pie graph:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.char.array(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct', 'Nov','Dec'])
    y = np.array([234, 64, 54,10, 0, 1, 0, 9, 2, 1, 7, 7])
    colors = ['yellowgreen','red','gold','lightskyblue','white','lightcoral','blue','pink', 'darkgreen','yellow','grey','violet','magenta','cyan']
    porcent = 100.*y/y.sum()
    
    patches, texts = plt.pie(y, colors=colors, startangle=90, radius=1.2)
    labels = ['{0} - {1:1.2f} %'.format(i,j) for i,j in zip(x, porcent)]
    
    sort_legend = True
    if sort_legend:
        patches, labels, dummy =  zip(*sorted(zip(patches, labels, y),
                                              key=lambda x: x[2],
                                              reverse=True))
    
    plt.legend(patches, labels, loc='left center', bbox_to_anchor=(-0.1, 1.),
               fontsize=8)
    
    plt.savefig('piechart.png', bbox_inches='tight')
    

    enter image description here


    EDIT: if you want to keep the legend in the original order, as you mentioned in the comments, you can set sort_legend=False in the code above, giving:

    enter image description here

    0 讨论(0)
  • 2020-12-13 20:25

    Try tightlayout.

    plt.tight_layout()
    

    at the end of your code. It may prevent the overlap a little bit.

    0 讨论(0)
提交回复
热议问题