一组子图的共同图例

Common legend for a group of subplots

如何显示子图组的通用图例(不是全部)。例如,每一列中的所有子图都有一个图例。

fig, ax = plt.subplots(nrows=4, ncols=2)

for row in range(0, 4):
    for col in range(0, 2):
        ax[row][col].legend(loc="upper right") 
        # This will add a legend for each sub plot.

fig.legend(loc="upper right")
# This will add a legend for whole figure. 
# Suggested here: 

相反,我需要的是每列(或行)的通用图例。当不同列中的图不同时,这可能很有用(例如,在我的例子中,第一列中的图是热图,第二列中的图是线图,这显然应该有不同的图例)。

你可以这样做:

fig, ax = plt.subplots(nrows=4, ncols=2)

for row in range(0, 4):
    for col in range(0, 2):
        if col == 1: # only for the last column, add a legend
            ax[row][col].legend(loc="upper right")