无法并排绘制Seaborn直方图:2行2布局解包值错误求助
问题原因与解决方法
这个错误的核心原因是当你创建2行2列的子图布局时,matplotlib返回的axes对象是一个二维数组(形状为(2,2)),而不是四个独立的变量。你尝试直接把它拆成ax1, ax2, ax3, ax4,但实际上它只返回了两个元素(每行一个一维数组),所以会报“expected 4, got 2”的错。
这里有两种简单的解决方式:
方式一:扁平化axes数组
把二维的axes数组转成一维,这样就能直接拆成四个独立的轴对象:
fig, axes = plt.subplots(nrows=2, ncols=2) # 用flatten()把二维数组转成一维 ax1, ax2, ax3, ax4 = axes.flatten() sns.distplot(iot['opex_euro'], ax=ax1) sns.distplot(iot['cost_of_delay'], ax=ax2) sns.distplot(iot['customer_commitment_value'], ax=ax3) sns.distplot(iot['ktlo_value'], ax=ax4) plt.show()
方式二:直接通过二维索引访问子图
不需要拆包,直接用axes[row_index, col_index]的方式指定每个子图的轴:
fig, axes = plt.subplots(nrows=2, ncols=2) sns.distplot(iot['opex_euro'], ax=axes[0, 0]) # 第一行第一列 sns.distplot(iot['cost_of_delay'], ax=axes[0, 1]) # 第一行第二列 sns.distplot(iot['customer_commitment_value'], ax=axes[1, 0]) # 第二行第一列 sns.distplot(iot['ktlo_value'], ax=axes[1, 1]) # 第二行第二列 plt.show()
额外提示
另外需要注意:sns.distplot已经被官方弃用了,推荐使用sns.histplot(专注绘制直方图)或者sns.displot(更灵活的Figure级绘图函数,无需手动指定轴对象)来替代,避免后续版本兼容性问题。
内容的提问来源于stack exchange,提问作者Raul Gonzales
相关产品推荐
相关产品推荐

