你可能想读一下
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()