绘制子图时如何修复“numpy.ndarray”对象没有属性“get_figure”

Ish*_*tta 7 python numpy matplotlib

我编写了以下代码来在不同的子图中绘制 6 个饼图,但出现错误。如果我只使用它来绘制 2 个图表,则此代码可以正常工作,但除此之外还会产生错误。

我的数据集中有 6 个分类变量,它们的名称存储在 list 中cat_cols。图表将根据训练数据绘制train

代码

fig, axes = plt.subplots(2, 3, figsize=(24, 10))

for i, c in enumerate(cat_cols):
  
  train[c].value_counts()[::-1].plot(kind = 'pie', ax=axes[i], title=c, autopct='%.0f', fontsize=18)
  axes[i].set_ylabel('')
    
plt.tight_layout()
Run Code Online (Sandbox Code Playgroud)

错误

AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'
Run Code Online (Sandbox Code Playgroud)

我们如何纠正这个问题?

Tre*_*ney 9

  • 问题是plt.subplots(2, 3, figsize=(24, 10))创建两组 3 个子图,而不是一组 6 个子图。
array([[<AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>],
       [<AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>]], dtype=object)
Run Code Online (Sandbox Code Playgroud)
array([[<AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>],
       [<AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>]], dtype=object)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明