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

问题描述 投票:0回答:1

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

据我所知 Seaborn 是基于 Matplotlib 的,我尝试在每个 countplot 函数后使用 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()

这是网格图本身: Seaborn Countplot Grid

range seaborn yaxis exploratory-data-analysis countplot
1个回答
0
投票

您可能想阅读

plt
ax
界面之间的区别
以及避免在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

© www.soinside.com 2019 - 2024. All rights reserved.