首页 > 解决方案 > 如何正确循环遍历 matplotlib 图形的子图以显示每条线的最终 y 轴值?

问题描述

我目前有一个带有 16 个子图、4 列和 4 行的 matplotlib 图。我生成了以下代码,该代码循环遍历每个子图并在 16 个子图中的每一个上绘制不同的数据:

fac_list = [one, two, three, four, five, six, seven, eight, nine, ten , eleven, twelve, 
thirteen, fourteen, fifteen, sixteen]
color = ['blue','red']

ds_i = 0
for row in range(0,subplot_shape[0]):
    for col in range(0,subplot_shape[1]):
        fac = fac_list[ds_i]
            plot('total', 
                    currentname=fac,
                    subplot_index=(row,col),
                    linestyle='-',
                    marker='.',
                    label='NEW',
                    color=color[0])
            leg2 = axes[row][col].legend(loc='upper left',bbox_to_anchor=(-0.10, 1.04), prop={'size':8},
                frameon=False, markerscale=0, handlelength=0)
            for line, text in zip(leg2.get_lines(), leg2.get_texts()):
                text.set_color(line.get_color())
            #axes[row][col].text(1.1,new_obj['total'].values[-1],new_obj['total'].values[-1],horizontalalignment='center',fontsize=5, rotation=45,
                #transform=axes[row][col].transAxes, color=color[0])
        ds_i += 1

目前,我已经知道了,因此注释掉的行仅显示 fac_list (十六)中最后一项的最终 y 轴值,但该值显示在我图中的每个子图上,而不仅仅是最后一个子图(即它应该显示在下面的子图)。如何正确循环子图,以便 fac_list 中每个项目的最终 y 轴值显示在每个相应的子图中(fac_list 中的一个显示在子图(0,0)上,fac_list 中的两个显示在子图(0 ,1)等)?到目前为止,我尝试过的任何方法都没有奏效。

标签: pythonloopsfor-loopmatplotlibyaxis

解决方案


取消注释该行并将其置于与列的 for 循环相同的缩进级别

for row in range(0,subplot_shape[0]):
    for col in range(0,subplot_shape[1]):
    ...
    ...

        for line, text in zip(leg2.get_lines(), leg2.get_texts()):
            text.set_color(line.get_color())

# Place the following line as it is in this answer
    axes[row][col].text(1.1,new_obj['total'].values[-1],new_obj['total'].values[-1],
                        horizontalalignment='center',fontsize=5, rotation=45,
                        transform=axes[row][col].transAxes, color=color[0])

推荐阅读