我有代码:
norm_reviews = pd.read_csv('fandango_scores.csv')
fig = plt.figure(figsize=(5, 20))
ax1 = fig.add_subplot(4, 1, 1)
ax2 = fig.add_subplot(4, 1, 2)
ax3 = fig.add_subplot(4, 1, 3)
ax4 = fig.add_subplot(4, 1, 4)
subplot_list = [ax1, ax2, ax3, ax4]
columns_for_visualization = ['Fandango_Ratingvalue', 'RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm']
for i in range(0, len(subplot_list)):
subplot_list[i] = subplot_list[i].hist(norm_reviews[columns_for_visualization[i]], bins=20, range=(0, 5))
subplot_list[i] = subplot_list[i].set_title('Distribution ' + columns_for_visualization[i])
plt.show()
问题是,循环中的第一行有效,但第二行不起作用:
subplot_list[i] = subplot_list[i].hist(norm_reviews[columns_for_visualization[i]], bins=20, range=(0, 5))
subplot_list[i] = subplot_list[i].set_title('Distribution ' + columns_for_visualization[i])
错误:
Traceback (most recent call last):
File "C:/ML/DataQuest/Data visualisazation/visualization.py", line 17, in <module>
subplot_list[i] = subplot_list[i].set_title('Distribution ' + columns_for_visualization[i])
AttributeError: 'tuple' object has no attribute 'set_title'
但是为什么第一行起作用?为什么第二行不起作用?
答案 0 :(得分:3)
这将起作用
for sub_plot, col_for_visualization in zip(subplot_list, columns_for_visualization):
sub_plot.hist(norm_reviews[col_for_visualization], bins=20, range=(0, 5))
sub_plot.set_title('Distribution ' + col_for_visualization )
plt.show()
代码不起作用的原因是,您实际上在第一行中重新分配了subplot_list[i]
的内容。到第二行时,内容不再是ax
对象,而是hist
函数返回的内容。
答案 1 :(得分:0)
我找到了解决方法:
for i in range(0, len(subplot_list)):
subplot_list[i].hist(norm_reviews[columns_for_visualization[i]], bins=20, range=(0, 5))
subplot_list[i].set_title('Distribution ' + columns_for_visualization[i])