2021年1月30日 星期六

[常見問題] Matplotlib - How to avoid overlapping of labels & autopct in a matplotlib pie chart?

 Source From Here

Question
My Python code is:
  1. import matplotlib.pyplot as plt  
  2.   
  3. values = [2346454,1001092177]  
  4. labels = ['Jan''Feb''Mar''Apr''May''Jun''Jul','Aug','Sep','Oct''Nov','Dec']  
  5.   
  6. colors = ['yellowgreen''red''gold''lightskyblue',   
  7.           'white','lightcoral','blue','pink''darkgreen',   
  8.           'yellow','grey','violet','magenta','cyan']  
  9.   
  10. plt.pie(values, labels=labels, autopct='%1.1f%%', shadow=True,   
  11.         colors=colors, startangle=90, radius=1.2)  
  12.   
  13. plt.show()  

Is it possible to show the labels "Jan", "Feb", "Mar", etc. and the percentages, either:
* Without overlapping, or
* Using an arrow mark?

HowTo
Alternatively you can put the legends beside the pie graph:
  1. import matplotlib.pyplot as plt  
  2. import numpy as np  
  3.   
  4. x = np.char.array(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct''Nov','Dec'])  
  5. y = np.array([2346454,1001092177])  
  6. colors = ['yellowgreen','red','gold','lightskyblue','white','lightcoral','blue','pink''darkgreen','yellow','grey','violet','magenta','cyan']  
  7. porcent = 100.*y/y.sum()  
  8.   
  9. patches, texts = plt.pie(y, colors=colors, startangle=90, radius=1.2)  
  10. labels = ['{0} - {1:1.2f} %'.format(i,j) for i,j in zip(x, porcent)]  
  11.   
  12. sort_legend = True  
  13. if sort_legend:  
  14.     patches, labels, dummy =  zip(*sorted(zip(patches, labels, y),  
  15.                                           key=lambda x: x[2],  
  16.                                           reverse=True))  
  17.   
  18. plt.legend(patches, labels, loc='best', bbox_to_anchor=(-0.11.), fontsize=8)  
  19. # plt.savefig('piechart.png', bbox_inches='tight')  



沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...