使用Seaborn Catplot出现额外空白图的原因及解决方法
解决Seaborn catplot生成额外空白图的问题
问题原因
你遇到的末尾空白图,本质是Seaborn的catplot是一个「Figure级函数」——它会自动创建一个全新的Figure对象来绘图,而你之前手动用plt.figure()和plt.axes()创建的空Figure/Axes根本没被catplot使用(而且catplot其实不支持直接传入自定义ax参数,你代码里传的ax会被直接忽略),最后这部分空的绘图区域就被单独渲染出来,变成了多余的空白图。
解决方法(保留自定义格式化需求)
根据你想要保留ax做额外格式化的需求,有两种靠谱的解决方案:
方案1:改用Axes级别的countplot(推荐)
Seaborn提供了Axes级别的统计绘图函数,比如sns.countplot(),它可以直接使用你手动创建的ax,不会生成多余的Figure。修改后的代码如下:
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline df1 = pd.DataFrame( {'category': {0: 'Cat', 1: 'Cat', 2: 'Cat', 3: 'Cat', 4: 'Dog', 5: 'Dog', 6: 'Dog', 7: 'Dog', 8: 'Dog', 9: 'Dog', 10: 'Dog', 11: 'Dog', 12: 'Dog', 13: 'Dog', 14: 'Dog', 15: 'Dog', 16: 'Dog', 17: 'Dog', 18: 'Dog', 19: 'Dog'}, 'shape': {0: 'Small', 1: 'Small', 2: 'Small', 3: 'Small', 4: 'Small', 5: 'Small', 6: 'Small', 7: 'Medium', 8: 'Medium', 9: 'Large', 10: 'Small', 11: 'Small', 12: 'Small', 13: 'Small', 14: 'Small', 15: 'Small', 16: 'Small', 17: 'Small', 18: 'Small', 19: 'Small'}} ) # 手动创建你需要的figure和axes,完全保留你的自定义设置 plt.figure(figsize=(5,5), facecolor='#ffffff') ax = plt.axes(facecolor='#ffffff') plt.xticks(rotation=25) # 改用Axes级别的countplot,传入自定义的ax sns.countplot(x='shape', hue='category', data=df1, ax=ax) # 继续做你的额外格式化操作 plt.xlabel('Diamond Shape') plt.show()
方案2:如果坚持用catplot,通过FacetGrid操作
如果你一定要用catplot(比如需要它的分面功能),那不要手动创建figure/ax,而是通过catplot返回的FacetGrid对象来获取axes并做格式化,这样也不会生成空白图:
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline df1 = pd.DataFrame( {'category': {0: 'Cat', 1: 'Cat', 2: 'Cat', 3: 'Cat', 4: 'Dog', 5: 'Dog', 6: 'Dog', 7: 'Dog', 8: 'Dog', 9: 'Dog', 10: 'Dog', 11: 'Dog', 12: 'Dog', 13: 'Dog', 14: 'Dog', 15: 'Dog', 16: 'Dog', 17: 'Dog', 18: 'Dog', 19: 'Dog'}, 'shape': {0: 'Small', 1: 'Small', 2: 'Small', 3: 'Small', 4: 'Small', 5: 'Small', 6: 'Small', 7: 'Medium', 8: 'Medium', 9: 'Large', 10: 'Small', 11: 'Small', 12: 'Small', 13: 'Small', 14: 'Small', 15: 'Small', 16: 'Small', 17: 'Small', 18: 'Small', 19: 'Small'}} ) # catplot会自动创建figure,返回FacetGrid对象 g = sns.catplot(x='shape', hue='category', kind='count', data=df1, height=5, aspect=1) # 通过FacetGrid获取axes,进行你的自定义格式化 ax = g.axes[0,0] ax.set_facecolor('#ffffff') g.figure.set_facecolor('#ffffff') ax.tick_params(axis='x', rotation=25) ax.set_xlabel('Diamond Shape') plt.show()
小总结
如果你只是想绘制单组计数图并保留自定义ax,方案1是最优选择——逻辑简单,完全贴合你原本的代码结构,还能彻底避免空白图问题。
内容的提问来源于stack exchange,提问作者william007
相关产品推荐
相关产品推荐

