对象'numpy.ndarray'对象上不可调用'AxesSubplot'错误



我正在尝试使用以下代码绘制几个相邻的饼图:

import matplotlib.pyplot as plt
list_categorical_column = ['gender','race/ethnicity','parental level of education','lunch','test preparation course']
dict_data = df['gender'].value_counts()
fig, ((ax1,ax2),(ax3,ax4),(ax5,ax6)) = plt.subplots(3,2,figsize=(10,10)) 
ax_list = [ax1, ax2, ax3, ax4, ax5, ax6]
i = 0
for column in list_categorical_column :
dict_data = df[column].value_counts()
ax_list[i].pie(list(dict_data.keys()), list(dict_data.values()))
ax_list[i].set_title(column)
i += 1
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.5)
plt.show()

但我得到了这个错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-9-d6c8c5c74b07> in <module>
7 for column in list_categorical_column :
8     dict_data = df[column].value_counts()
----> 9     ax_list[i].pie(list(dict_data.keys()), list(dict_data.values()))
10     ax_list[i].set_title(column)
11     i +=1
TypeError: 'numpy.ndarray' object is not callable

当我尝试遍历ax对象时,它会返回以下错误:

ax1[1,1]
TypeError                                 Traceback (most recent call last)
<ipython-input-11-e981b338b40e> in <module>
4 ax_list=[ax1,ax2,ax3,ax4,ax5,ax6]
5 i=0
----> 6 ax1[1,1]
7 for column in list_categorical_column :
8     dict_data = df[column].value_counts()
TypeError: 'AxesSubplot' object is not subscriptable

我在这里做错了什么?

pd.Series.value_counts方法将pd.Series类型返回到dict_data中。因此,当执行dict_data.values()时,将对pd.Series.values属性执行函数调用,该属性具有np.ndarray类型。这应该有效:

import matplotlib.pyplot as plt
list_categorical_column = ['gender','race/ethnicity','parental level of education','lunch','test preparation course']
dict_data = df['gender'].value_counts()
fig, ((ax1,ax2),(ax3,ax4),(ax5,ax6)) = plt.subplots(3,2,figsize=(10,10)) 
ax_list = [ax1,ax2,ax3,ax4,ax5,ax6]
i = 0
for column in list_categorical_column:
dict_data = df[column].value_counts().to_dict()
ax_list[i].pie(list(dict_data.keys()), list(dict_data.values()))
ax_list[i].set_title(column)
i += 1
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.5)
plt.show()

最新更新