【问题标题】:global legend for all subplots所有子图的全局图例
【发布时间】:2017-01-03 00:57:11
【问题描述】:

我创建了一个 n x n 的 matplot 子图矩阵,其中包含相同类型的曲线(我们将它们命名为 signal1 和 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”的图形全局图例,而不是将相同的图例附加到每个子图中。

我该怎么做?

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    一种方法是在地块下方强制留出一些额外空间。然后,您可以在此处放置图例并拥有一个“全局”图例。

    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()
    

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

    对我来说,输出图看起来像

    这是你想要的吗?

    【讨论】:

    • 感谢您的帮助 - 我想出的解决方案是将图例添加到第一个子图中。但你的更好更干净。
    猜你喜欢
    • 1970-01-01
    • 2017-12-10
    • 2011-11-23
    • 2021-05-03
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2012-01-02
    • 2019-02-08
    相关资源
    最近更新 更多