如何为周期中的每个子图创建图例?

时间:2019-03-18 16:56:08

标签: python matplotlib

我有子图,我正在尝试为每个子图设置图例:

fig,ax = plt.subplots(2,2,figsize = (20,20))
for el in dict_for_genders['Means']:
    ax[0,0].plot(['Chapter ' + str(x) for x in range(1,7)],dict_for_genders['Means'][el])

for el in dict_for_genders['Count_viewers']:
    ax[0,1].plot(['Chapter ' + str(x) for x in range(1,7)],dict_for_genders['Count_viewers'][el])

for key,value in dict_for_genders['Count fans Star wars'].items():
    ax[1,0].hist(x = key, weights = value)

for key,value in dict_for_genders['Count fans Star Trek'].items():
    ax[1,1].hist(x = key, weights = value)

for each_ax in ax:
    each_ax.legend(['Male','Female'])

我有错误:

Traceback (most recent call last):
  File "C:/ML/DataQuest/DataCleaning/Star wars project/star_wars_project.py", line 244, in <module>
    each_ax.legend(['Male','Female'])
AttributeError: 'numpy.ndarray' object has no attribute 'legend'

如何在一个循环中为每个轴设置图例?

1 个答案:

答案 0 :(得分:1)

.map(|word| word.trim_end_matches(char::is_alphanumeric)) 是形状为(2,2)的2D数组。因此,ax是形状为(2,)的一维数组。您必须分别访问每个元素。例如:

each_ax