Matplotlib显示两个空图问题:尝试并排绘制Seaborn联合图布局异常排查
解决Seaborn Jointplot并排布局异常的问题
你遇到的问题核心在于 Seaborn的jointplot函数本身会自动创建一个新的Figure对象,而不是复用你通过plt.subplots()创建的子图轴(ax1/ax2)。这就导致你手动创建的1行2列子图根本没被使用,最后先显示了空的子图布局,然后jointplot各自生成了独立的纵向排列的图。
要解决这个问题,我们需要用Seaborn的JointGrid类来手动构建联合图,这样就能指定到已有的子图中。下面是修正后的代码:
import matplotlib.pyplot as plt import seaborn as sns # 创建1行2列的子图布局 fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 8)) # 第一个联合图:Price vs Bedrooms g1 = sns.JointGrid(x=df['target'], y=df['bedrooms'], space=0, ax=ax1) g1.plot_joint(sns.scatterplot, alpha=0.5, color='r') g1.plot_marginals(sns.histplot, color='r', kde=True) # 设置轴限制和标签 g1.ax_joint.set_xlim(0, 5) g1.ax_joint.set_ylim(0, 10) g1.set_axis_labels(xlabel='Price', ylabel='Number of bedrooms') # 第二个联合图:Price vs Bathrooms g2 = sns.JointGrid(x=df['target'], y=df['bathrooms'], space=0, ax=ax2) g2.plot_joint(sns.scatterplot, alpha=0.5, color='b') g2.plot_marginals(sns.histplot, color='b', kde=True) # 设置轴限制和标签 g2.ax_joint.set_xlim(0, 5) g2.ax_joint.set_ylim(0, 10) g2.set_axis_labels(xlabel='Price', ylabel='Number of bathrooms') plt.tight_layout() plt.show()
关键说明:
- 使用
JointGrid替代jointplot:JointGrid是jointplot的底层类,允许我们指定要使用的子图轴(通过ax参数),从而复用我们创建的布局。 space=0:调整联合图和边际图之间的间距,让布局更紧凑。- 手动调用
plot_joint和plot_marginals:分别绘制散点图(主图)和边际分布(直方图/密度图),你可以根据需求替换成其他绘图函数(比如kdeplot)。 - 通过
ax_joint设置轴限制:因为JointGrid的主图轴需要通过ax_joint属性访问,而不是直接用plt.xlim。
另外,如果你还是想使用jointplot,可以通过控制plt.figure的方式,但这种方法不如JointGrid可靠,因为jointplot依然会创建新的figure,需要手动调整布局。不过更推荐上面的JointGrid方案,它更灵活且符合你的布局需求。
内容的提问来源于stack exchange,提问作者Zexxxx
相关产品推荐
相关产品推荐

