我绘制了相同类型的信息,但针对不同的国家,使用Matplotlib绘制了多个子图。也就是说,我在一个3x3网格上有9个图,所有的线都是相同的(当然,每条线的值不同)。

然而,我还没有弄清楚如何将一个图例(因为所有九个子图都有相同的线条)放在图形上一次。

我怎么做呢?


当前回答

如果您正在使用柱状图的子图,每个柱状图都有不同的颜色,那么使用mpatch自己创建工件可能会更快。

假设你有四个不同颜色的条,分别是r、m、c和k,你可以这样设置图例:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
labels = ['Red Bar', 'Magenta Bar', 'Cyan Bar', 'Black Bar']


#####################################
# Insert code for the subplots here #
#####################################


# Now, create an artist for each color
red_patch = mpatches.Patch(facecolor='r', edgecolor='#000000') # This will create a red bar with black borders, you can leave out edgecolor if you do not want the borders
black_patch = mpatches.Patch(facecolor='k', edgecolor='#000000')
magenta_patch = mpatches.Patch(facecolor='m', edgecolor='#000000')
cyan_patch = mpatches.Patch(facecolor='c', edgecolor='#000000')
fig.legend(handles = [red_patch, magenta_patch, cyan_patch, black_patch], labels=labels,
       loc="center right",
       borderaxespad=0.1)
plt.subplots_adjust(right=0.85) # Adjust the subplot to the right for the legend

其他回答

Figlegend可能就是您要找的:matplotlib.pyplot.figlegend

一个例子是在图图例演示。

另一个例子:

plt.figlegend(lines, labels, loc = 'lower center', ncol=5, labelspacing=0.)

Or:

fig.legend(lines, labels, loc = (0.5, 0), ncol=5)

你只需要在循环之外请求一次图例。

例如,在这种情况下,我有4个子情节,具有相同的线,和一个图例。

from matplotlib.pyplot import *

ficheiros = ['120318.nc', '120319.nc', '120320.nc', '120321.nc']

fig = figure()
fig.suptitle('concentration profile analysis')

for a in range(len(ficheiros)):
    # dados is here defined
    level = dados.variables['level'][:]

    ax = fig.add_subplot(2,2,a+1)
    xticks(range(8), ['0h','3h','6h','9h','12h','15h','18h','21h']) 
    ax.set_xlabel('time (hours)')
    ax.set_ylabel('CONC ($\mu g. m^{-3}$)')

    for index in range(len(level)):
        conc = dados.variables['CONC'][4:12,index] * 1e9
        ax.plot(conc,label=str(level[index])+'m')

    dados.close()

ax.legend(bbox_to_anchor=(1.05, 0), loc='lower left', borderaxespad=0.)
         # it will place the legend on the outer right-hand side of the last axes

show()

对于在具有多个轴的图形中自动定位单个图例,例如使用subplots()获得的图例,以下解决方案非常有效:

plt.legend(lines, labels, loc = 'lower center', bbox_to_anchor = (0, -0.1, 1, 1),
           bbox_transform = plt.gcf().transFigure)

使用bbox_to_anchor和bbox_transform=plt.gcf()。transFigure,你正在定义一个新的边界框的大小你的数字作为loc的参考。使用(0,-0.1,1,1)将这个边界框略微向下移动,以防止图例被放置在其他艺术家之上。

OBS:在使用fig.set_size_inch()之后和使用fig.tight_layout()之前使用这个解决方案

如果您正在使用柱状图的子图,每个柱状图都有不同的颜色,那么使用mpatch自己创建工件可能会更快。

假设你有四个不同颜色的条,分别是r、m、c和k,你可以这样设置图例:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
labels = ['Red Bar', 'Magenta Bar', 'Cyan Bar', 'Black Bar']


#####################################
# Insert code for the subplots here #
#####################################


# Now, create an artist for each color
red_patch = mpatches.Patch(facecolor='r', edgecolor='#000000') # This will create a red bar with black borders, you can leave out edgecolor if you do not want the borders
black_patch = mpatches.Patch(facecolor='k', edgecolor='#000000')
magenta_patch = mpatches.Patch(facecolor='m', edgecolor='#000000')
cyan_patch = mpatches.Patch(facecolor='c', edgecolor='#000000')
fig.legend(handles = [red_patch, magenta_patch, cyan_patch, black_patch], labels=labels,
       loc="center right",
       borderaxespad=0.1)
plt.subplots_adjust(right=0.85) # Adjust the subplot to the right for the legend

使用Matplotlib 2.2.2,可以使用gridspec特性来实现这一点。

在下面的例子中,目标是以2x2的方式排列四个子情节,并在底部显示图例。在底部创建一个“人造”轴,将图例放置在固定的位置。“人造”轴然后关闭,所以只有传说显示。结果:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# Gridspec demo
fig = plt.figure()
fig.set_size_inches(8, 9)
fig.set_dpi(100)

rows   = 17 # The larger the number here, the smaller the spacing around the legend
start1 = 0
end1   = int((rows-1)/2)
start2 = end1
end2   = int(rows-1)

gspec = gridspec.GridSpec(ncols=4, nrows=rows)

axes = []
axes.append(fig.add_subplot(gspec[start1:end1, 0:2]))
axes.append(fig.add_subplot(gspec[start2:end2, 0:2]))
axes.append(fig.add_subplot(gspec[start1:end1, 2:4]))
axes.append(fig.add_subplot(gspec[start2:end2, 2:4]))
axes.append(fig.add_subplot(gspec[end2, 0:4]))

line, = axes[0].plot([0, 1], [0, 1], 'b')         # Add some data
axes[-1].legend((line,), ('Test',), loc='center') # Create legend on bottommost axis
axes[-1].set_axis_off()                           # Don't show the bottom-most axis

fig.tight_layout()
plt.show()