我有一個按降序Count排列的資料框,看起來像這樣:
df = pd.DataFrame({'Topic': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'],
'Count': [80, 75, 70, 65, 60, 55, 50, 45, 40, 35, 30, 25, 20]})
但有超過 50 行。
我想為前 10 個主題創建一個餅圖,并將其余主題匯總起來,并將其百分比表示為Others餅圖中的標簽“”。是否可以針對每個餅圖排除餅圖示簽,并在圖例中單獨提及它們?
期待中的感謝
uj5u.com熱心網友回復:
替換Topic為Otherif no top Nin

圖例中的百分比:
N = 5
df2 = df.iloc[:N]
df2 = df2.append({'Topic': 'Other', 'Count': df['Count'].iloc[N:].sum()}, ignore_index=True)
df2.set_index('Topic').plot.pie(y='Count', legend=False)
leg = plt.legend(labels=df2['Count'])
輸出:

uj5u.com熱心網友回復:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'Topic': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'],
'Count': [80, 75, 70, 65, 60, 55, 50, 45, 40, 35, 30, 25, 20]})
df.index = df.Topic
plot = df.plot.pie(y='Count', figsize=(5, 5))
plt.show()
使用檔案:https ://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.pie.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414808.html
標籤:
