python - matplotlib 中不需要的空白子图

标签 python matplotlib seaborn

Plots

我是 matplotlib 和 seaborn 的新手,目前正在尝试使用经典的 titanic 数据集练习这两个库。这可能是基本的,但我正在尝试通过输入参数 ax = matplotlib axis 并排绘制两个因子图,如下面的代码所示:

import matploblib.pyplot as plt
import seaborn as sns
%matplotlib inline 

fig, (axis1,axis2) = plt.subplots(1,2,figsize=(15,4))
sns.factorplot(x='Pclass',data=titanic_df,kind='count',hue='Survived',ax=axis1)
sns.factorplot(x='SibSp',data=titanic_df,kind='count',hue='Survived',ax=axis2)

我原以为这两个因子图是并排的,但不仅如此,我还得到了两个额外的空白子图,如上所示

已编辑:图像不存在

最佳答案

任何调用 sns.factorplot()实际上创建了一个新图形,尽管内容被绘制到现有轴( axes1axes2 )。这些数字与原始 fig 一起显示.

我想防止那些未使用的数字出现的最简单方法是关闭它们,使用 plt.close(<figure number>) .

这是笔记本的解决方案

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
%matplotlib inline

titanic_df = pd.read_csv(r"https://github.com/pcsanwald/kaggle-titanic/raw/master/train.csv")

fig, (axis1,axis2) = plt.subplots(1,2,figsize=(15,4))
sns.factorplot(x='pclass',data=titanic_df,kind='count',hue='survived',ax=axis1)
sns.factorplot(x='sibsp',data=titanic_df,kind='count',hue='survived',ax=axis2)
plt.close(2)
plt.close(3)

(对于普通控制台绘图,删除 %matplotlib inline 命令并在末尾添加 plt.show()。)

关于python - matplotlib 中不需要的空白子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41570747/

相关文章:

python - 从 seaborn 中保存情节

python - 如何用渐变填充 matplotlib 条形图?

python-3.x - 来自列表而不是数据框的 Seaborn 条形图

python - 在 python 中通过服务器路由消息

python - 如何在 Python 的 seaborn 中将 tsplot 与 FacetGrid 一起使用?

python - 填充matplotlib线图的上方/下方

python - 如何在 Python 图中以弧度为单位设置 y 轴?

LAB和灰度之间的Python OpenCV色彩空间差异

python - 导入模块时抑制 scapy 警告消息

python - 使用 scrapy-splash 选择依赖下拉菜单