我必須為以下資料制作餅圖:

但是,由于較大的數字為數百而較小的數字小于 1,因此由于重疊,圖形的標簽最終難以辨認。例如,這是新加坡的圖表:

我曾嘗試減小字體大小并增加圖形大小,但因為它重疊太多,所以這樣做根本沒有幫助。以下是我的圖表的必要代碼:
import matplotlib.pyplot as plt
plt.pie(consumption["Singapore"], labels = consumption.index)
fig = plt.gcf()
fig.set_size_inches(8,8)
ax = plt.gca()
handles, labels = ax.get_legend_handles_labels()
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0], reverse=True))
plt.show()
有沒有辦法解決這個問題?
uj5u.com熱心網友回復:
標簽字符重疊的問題不能通過編程完全解決。如果您只處理您的挑戰,請首先將它們分組以匯總標簽數量。分組資料框以餅圖為目標。但是還是有重疊的,所以獲取當前標簽位置,改變重疊標簽的位置。
new_df = consumption.groupby('Singapore')['Entity'].apply(list).reset_index()
new_df['Entity'] = new_df['Entity'].apply(lambda x: ','.join(x))
new_df
Singapore Entity
0 0.000000 Biofuels,Wind,Hydro,Nuclear
1 0.679398 Other
2 0.728067 Solar
3 5.463305 Coal
4 125.983605 Gas
5 815.027694 Oil
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8,8))
wedges, texts = ax.pie(new_df["Singapore"], wedgeprops=dict(width=0.5), startangle=0, labels=new_df.Entity)
# print(wedges, texts)
texts[0].set_position((1.1,0.0))
texts[1].set_position((1.95,0.0))
texts[2].set_position((2.15,0.0))
plt.legend()
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/457254.html
標籤:Python matplotlib 饼形图
