使用循环创建seaborn displot时报错且图形形态异常如何解决
问题核心原因
- 你混淆了Seaborn的axes级接口和figure级接口:
sns.displot是figure级绘图函数,调用时会自动创建独立的新画布,不会使用你通过plt.subplot预先声明的子图坐标系。这就导致预创建的子图全部为空,同时每个循环都会单独输出一张displot图,最终排版完全混乱。 - 你硬编码了子图网格为10行2列,如果你要绘制的字段总数超过20,
plt.subplot的索引会超出范围,直接触发运行时错误。
修复方案
改用axes级的分布绘图函数sns.histplot,它可以直接在你指定的子图坐标系上绘制,适配你预创建的子图网格,参考代码如下:
import seaborn as sns import matplotlib.pyplot as plt columns = list(cols) # cols created from dataframe.columns sns.set(rc = {"figure.figsize": (12, 15)}) sns.set_style(style = "white") # 动态计算需要的行数,每行2张图 row_num = (len(columns) + 1) // 2 for i in range(len(columns)): ax = plt.subplot(row_num, 2, i + 1) # 用axes级的histplot替代displot,指定绘制在当前子图ax上 sns.histplot(data[columns[i]], rug=True, ax=ax) # 可选:设置子图标题 ax.set_title(f"Distribution of {columns[i]}") # 自动调整子图间距避免重叠 plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者eh329
相关产品推荐
相关产品推荐

