我目前使用的資料集顯示了客戶及其班級。
Customer Class
4124 A
4123 A
532 B
4512 A
5325 B
642 C
5345 A
我正在使用 matplotlib 繪制頻率條形圖:
class_f=df.groupby(['Class']).size().reset_index(name='Frequency').sort_values('Frequency', ascending=False)
plt.bar(class_f['Class'].astype(str), class_f['Frequency'])
plt.show()
但我想使用歸一化圖和 y 軸上的百分比值來可視化結果。對于百分比值,我一直在嘗試使用 mtick。對于歸一化圖,我發現了很多帶有堆疊圖和使用 seaborn 的示例。我想知道如何使用 matplotlib 做同樣的事情。
uj5u.com熱心網友回復:
以下代碼說明了 3 個不同的圖:
- 從聚合資料框創建的 matplotlib 條形圖,按降序排列
- seaborn histplot with
stat='percent'(使用遇到類的順序) - seaborn histplot
multiple='fill'其中顯示了每個類的相對比例;通常使用來自另一列的 x 軸;如果沒有,可以使用一個虛擬的零陣列來只有一個 x 位置
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
import seaborn as sns
import pandas as pd
import numpy as np
df = pd.DataFrame({'Customer': np.random.randint(1000, 10000, 30),
'Class': np.random.choice(['A', 'B', 'C'], 30)})
class_f = df.groupby(['Class']).size().reset_index(name='Frequency').sort_values('Frequency', ascending=False)
fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(14, 4))
ax1.bar(class_f['Class'], class_f['Frequency'] / class_f['Frequency'].sum() * 100)
ax1.yaxis.set_major_formatter(PercentFormatter(100, decimals=0))
sns.histplot(data=df, x='Class', stat='percent', ax=ax2)
ax2.yaxis.set_major_formatter(PercentFormatter(100, decimals=0))
sns.histplot(data=df, x=np.zeros(len(df)), stat='percent', hue='Class', multiple='fill', ax=ax3)
ax3.yaxis.set_major_formatter(PercentFormatter(1))
ax3.set_xticks([])
plt.tight_layout()
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/378616.html
標籤:Python 熊猫 matplotlib
