如何在 Matplotlib 餅圖中避免標籤和 autopct 重疊?
為避免 matplotlib 餅圖中的標籤和autopct 重疊,我們可以將標籤作為圖例,使用legend() 方法。
步驟
初始化一個變數n=20 以獲取餅圖中的部分數量。
使用 numpy 建立切片和活動。
使用十六進位制字母建立隨機顏色,範圍為 20。
使用pie() 方法繪製餅圖,其中切片、顏色和切片資料點作為標籤。
列出標籤(這些標籤使用autopct 重疊)。
使用legend() 方法避免標籤和 autopct 重疊。
要顯示圖形,請使用 show() 方法。
示例
import random
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
n = 20
slices = np.arange(n)
activities = np.arange(n)
colors = ["#" + ''.join([random.choice('0123456789ABCDEF') for j in range(6)])
for i in range(n)]
patches, texts = plt.pie(slices,
colors=colors,
startangle=90,
labels=slices)
labels = ['{0} - {1:1.2f} %'.format(i, j) for i, j in zip(activities,
100.*slices/slices.sum())]
plt.legend(patches, labels, loc='center left', bbox_to_anchor=(-0.35, .5), fontsize=8)
plt.show()輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP