簡體   English   中英

Matplotlib通過海洋圖的軸在多個子圖中循環

[英]Matplotlib loop through axes in a seaborn plot for multiple subplots

我想在一個海洋直方圖(分布圖)上創建五個子圖(一個數據框的特定列中的每個類別一個)。

我的數據集是:

prog score
cool 1.9
cool 3.7
yay  4.5
yay  2.6
neat 1.4
neat 7
neat 6
wow  4.1
wow  1.7
wow  1.4
hooray 6.6
hooray 5.6
hooray 4.9
yikes 1.2
yikes 3.9
yikes 6.9

我不希望繪制所有 “程序”,而只希望列表中的每個:

prog_list = ['cool', 'yay', 'neat', 'yikes', 'wow']
scores = df['score']
f, axes = plt.subplots(3, 2, figsize=(15, 15))
# Delete last chart since there are only 5 subplots I need
f.delaxes(ax = axes[2,1])

for i, axes in enumerate(f.axes):
scores = df.loc[(df['prog'] == prog_list[i])]['score']
    axes = sns.distplot(scores, norm_hist=True, color='b')
    sigma = round(scores.std(), 3)
    mu = round(scores.mean(), 2)
    axes.set_xlim(1,7)
    axes.set_xticks(range(2,8))
    axes.set_xlabel('Score - Mean: {} (σ {})'.format(mu, sigma))
    axes.set_ylabel('Density')

但是,當我這樣做時,它只是將每個子集繪制到相同的圖上(這很酷,但絕對不是我想要的)。

在此處輸入圖片說明

嘗試這個:

# your code use axes and redefine it after every iteration
# I think this would be better
for prog, ax in zip(prog_list, axes.flatten()[:5]):
    scores = df.loc[(df['prog'] == prog)]['score']

    # note how I put 'ax' here
    sns.distplot(scores, norm_hist=True, ax=ax, color='b')

    # change all the axes into ax
    sigma = round(scores.std(), 3)
    mu = round(scores.mean(), 2)
    ax.set_xlim(1,7)
    ax.set_xticks(range(2,8))
    ax.set_xlabel('Score - Mean: {} (σ {})'.format(mu, sigma))
    ax.set_ylabel('Density')

plt.show()

輸出:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM