Matplotlib loop through axes in a seaborn plot for multiple subplots

后端 未结 1 856
梦毁少年i
梦毁少年i 2021-01-25 23:55

I\'d like to create five subplots (one for each category in a specific column of a dataframe) on a seaborn histogram (distplot).

My dataset is:

prog scor         


        
相关标签:
1条回答
  • 2021-01-26 00:23

    Try this:

    # 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()
    

    Output:

    0 讨论(0)
提交回复
热议问题