本文介绍了绘制子图时如何修复“numpy.ndarray"对象没有属性“get_figure"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了以下代码来在不同的子图中绘制6个饼图,但出现错误.如果我只使用它来绘制 2 个图表,则此代码可以正常工作,但除此之外还会产生错误.
我的数据集中有 6 个分类变量,它们的名称存储在列表 cat_cols
中.图表将根据训练数据 train
绘制.
代码
fig,axes = plt.subplots(2,3,figsize =(24,10))对于 i, c in enumerate(cat_cols):train[c].value_counts()[::-1].plot(kind = 'pie', ax=axes[i], title=c, autopct='%.0f', fontsize=18)轴[i].set_ylabel('')plt.tight_layout()
错误
AttributeError:'numpy.ndarray'对象没有属性'get_figure'
我们如何纠正这个问题?
解决方案
- 问题在于
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)
- 使用
axes.ravel()
从axes
解压缩所有子图数组.-
I have written the following code to plot 6 pie charts in different subplots, but I get an error. This code works correctly if I use it to plot only 2 charts, but produces an an error for anything more than that.
I have 6 categorical variables in my dataset, the names of which are stored in the list
cat_cols
. The charts are to be plotted from the training datatrain
.CODE
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()
ERROR
AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'
How do we rectify this?
解决方案- The issue is
plt.subplots(2, 3, figsize=(24, 10))
creates two groups of 3 subplots, not one group of six subplots.
array([[<AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>], [<AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>]], dtype=object)
- Unpack all of the subplot arrays from
axes
, usingaxes.ravel()
.numpy.ravel
, which returns a flattened array.- A list comprehension will also work,
axe = [sub for x in axes for sub in x]
- Assign each plot to one of the subplots in
axe
. - How to resolve AttributeError: 'numpy.ndarray' object has no attribute 'get_figure' when plotting subplots is a similar issue.
import pandas as pd import numpy as np # sinusoidal sample data sample_length = range(1, 6+1) rads = np.arange(0, 2*np.pi, 0.01) data = np.array([np.sin(t*rads) for t in sample_length]) df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name='radians'), columns=[f'freq: {i}x' for i in sample_length]) # crate the figure and axes fig, axes = plt.subplots(2, 3, figsize=(24, 10)) # unpack all the axes subplots axe = axes.ravel() # assign the plot to each subplot in axe for i, c in enumerate(df.columns): df[c].plot(ax=axe[i])
这篇关于绘制子图时如何修复“numpy.ndarray"对象没有属性“get_figure"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
- The issue is
-