代码之家  ›  专栏  ›  技术社区  ›  Noah J

将Seaborn/Matplotlib计数图的y轴范围设置为高于/低于最大和最小数据点的指定范围

  •  0
  • Noah J  · 技术社区  · 1 年前

    我正在为一个机器学习项目做EDA,并正在用Seaborn绘制一个计数图网格。在可视化中,由于y轴从0开始,并且有许多观察结果,因此每个子图中条形的高度差异几乎无法察觉。我想将每个图的y轴范围设置为高于/低于其最大和最小数据点的范围。

    据我所知,Seaborn是基于Matplotlib的,我尝试在每个计数图函数后使用plt.ylim(a,b)或ax.set(ylim=(a,b)),但这只会改变右下角子图(字幕启用)的y轴范围。

    非常感谢您帮助我将其应用于我定义的绘图函数中的每个子绘图。

    我用来生成绘图网格的代码如下:

    # Figure dimensions
    fig, axes = plt.subplots(5, 2, figsize = (18, 18))
    
    # List of categorical features column names
    categorical_features_list = list(categorical_features)
    
    # Countplot function
    def make_countplot():
        i = 0
        for n in range(0,5):
            m = 0
            sns.countplot(ax = axes[n, m], x = categorical_features_list[i], data = train_df, color = 'blue',
                          order = train_df[categorical_features_list[i]].value_counts().index);
            m += 1
            sns.countplot(ax = axes[n, m], x = categorical_features_list[i+1], data = train_df, color = 'blue', 
                          order = train_df[categorical_features_list[i+1]].value_counts().index);
            m -= 1
            i += 2
            
    make_countplot()
    

    以下是plotgrid本身: Seaborn Countplot Grid

    1 回复  |  直到 1 年前
        1
  •  1
  •   JohanC    1 年前

    你可能想读一下 the difference between the plt and the ax interface 以及about avoiding indices in Pytho 。你可以打电话 ax.set_ylim(...) 设置特定子地块的y限制。

    以下是一个使用Seaborn的巨大数据集的示例:

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    titanic = sns.load_dataset('titanic')
    
    categorical_features = ['survived', 'sex', 'sibsp', 'parch', 'class', 'who', 'deck', 'embark_town']
    
    # Figure dimensions
    fig, axes = plt.subplots((len(categorical_features) + 1) // 2, 2, figsize=(10, 15))
    
    for feature, ax in zip(categorical_features, axes.flat):
        counts = titanic[feature].value_counts()
        sns.countplot(ax=ax, x=feature, data=titanic, color='dodgerblue',
                      order=counts.index)
        min_val = counts.min()
        max_val = counts.max()
        # set the limits 10% higher than the highest and 10% lower than the lowest
        delta = (max_val - min_val) * 0.10
        ax.set_ylim(max(0, min_val - delta), max_val + delta)
        # remove the xlabel and set the feature name inside the plot (to save some space)
        ax.set_xlabel('')
        ax.text(0.5, 0.98, feature, fontsize=14, transform=ax.transAxes, ha='center', va='top')
    
    plt.tight_layout()
    plt.show()
    

    seaborn countplot with custom y limits

    推荐文章