本文介绍了所有子图的全局图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个包含相同类型曲线的 matplot 子图的 n x n 矩阵(让它们命名为 signal1 和 signal2):

I create an n x n matrix of matplot subplots which contain the same type of curve (lets name them signal1 and signal2):

n=5
f, axarr = plt.subplots(n,n)
for i,signal_generator in enumerate(signal_generators):
  y=i%n
  x=(i-y)/n
  axarr[x, y].plot(signal_generator.signal1)
  axarr[x, y].plot(signal_generator.signal2)

由于每个子图中的 2 个信号都代表相同的类型,我想使用带有两个条目signal1"signal2"的图形全局图例,而不是将相同的图例附加到每个子图中.

Since the 2 signals in each subplot each represent the same types, I want to use a figure global legend with the two entries 'signal1' 'signal2', rather then attaching the same legend to each subplot.

我该怎么做?

推荐答案

一种方法是强制在绘图下方留出一些额外空间.然后,您可以在此处安装图例,并拥有一个全局"图例.

One way to do it is to force some extra space below the plots. Then you can fit the legend right there and have one "global" legend.

import matplotlib.pyplot as plt
import numpy as np

plt.close('all')

fig, axlist = plt.subplots(3, 3)
for ax in axlist.flatten():
    line1, = ax.plot(np.random.random(100), label='data1')
    line2, = ax.plot(np.random.random(100), label='data2')
    line3, = ax.plot(np.random.random(100), 'o', label='data3')

fig.subplots_adjust(top=0.9, left=0.1, right=0.9, bottom=0.12)  # create some space below the plots by increasing the bottom-value
axlist.flatten()[-2].legend(loc='upper center', bbox_to_anchor=(0.5, -0.12), ncol=3)
# it would of course be better with a nicer handle to the middle-bottom axis object, but since I know it is the second last one in my 3 x 3 grid...

fig.show()

由于 bbox_to_anchor=(x, y) 具有负 y 值,现在倒数第二个(底部中间)轴区域下方将有一个标签.根据您有多少个不同的子图,以及您在每个子图中绘制了多少条不同的线,最好正确跟踪不同的线对象.也许将它们附加到列表中.

Now there will be an label below the second last (bottom middle) axis area, thanks to the bbox_to_anchor=(x, y) with a negative y-value. Depending on how many different subplots you have, and how many different lines you plot in each subplot it might be better to keep proper track of the different line-objects. Maybe append them to a list.

对我来说,输出数字看起来像

For me it the output figure looks like

这是否给您想要的东西?

Does this give you want you were looking for?

这篇关于所有子图的全局图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:55