代码之家  ›  专栏  ›  技术社区  ›  Tassou

扩展图例超过2个子图

  •  4
  • Tassou  · 技术社区  · 7 年前

    我如何让同一个图例出现在2个子图上,并使其扩展到2个子图上。有人知道,如果每个子图的y标签相同,我是否必须分别精确(该图用于科学论文)?我知道后一个问题与计算无关,但如果有人知道答案,我将不胜感激。

    对于图例的放置,我使用:

            ax[0].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                   ncol= 4, mode="expand", borderaxespad=0)
    

    plots

    2 回复  |  直到 7 年前
        1
  •  5
  •   user812786 bojeil    7 年前

    要使图例在两个子图之间拉伸,需要调整给定给的坐标 bbox_to_anchor .使用 2.2 f.tightlayout()

    下面是一个简单的工作示例:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x1 = np.linspace(0.0, 2.0)
    x2 = np.linspace(0.0, 2.0)
    
    y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
    y2 = np.cos(2 * np.pi * x2)
    
    f,ax = plt.subplots(1, 2)
    
    ax[0].plot(x1, y1, 'ko-', label='Damped')
    ax[0].plot(x2, y2, 'r.-', label='Undamped')
    ax[1].plot(x1, y1, 'ko-', label='Damped')
    ax[1].plot(x2, y2, 'r.-', label='Undamped')
    
    ax[0].legend(bbox_to_anchor=(0., 1.02, 2.2, .102), loc=3,
                   ncol=4, mode="expand", borderaxespad=0)
    
    plt.show()
    

    结果如下:

    enter image description here

        2
  •  2
  •   ImportanceOfBeingErnest    7 年前

    要跨地物中的所有子图拉伸图例,可以半自动放置图例。使用 subplotpars bbox_to_anchor 论点这需要通过 bbox_transform 论点然后,您需要手动指定的唯一参数是轴和图例之间的间距(在下面的示例中为0.02)和图例的高度(在下面的示例中为0.05),两者均以图形高度为单位。

    s = fig.subplotpars
    bb=[s.left, s.top+0.02, s.right-s.left, 0.05 ]
    leg = axes[0].legend(..., bbox_to_anchor=bb, mode="expand", borderaxespad=0,
                         bbox_transform=fig.transFigure)
    

    import matplotlib.pyplot as plt
    import numpy as np
    
    a = np.cumsum(np.random.rand(10,8), axis=0)
    
    fig, axes = plt.subplots(ncols=2)
    
    for i in range(a.shape[1]):
        axes[i//4].plot(a[:,i], marker="s", label="Label {}".format(i))
    
    s = fig.subplotpars
    bb=[s.left, s.top+0.02, s.right-s.left, 0.05 ]
    leg = axes[0].legend(loc=8, bbox_to_anchor=bb, ncol= 4, mode="expand", borderaxespad=0,
                    bbox_transform=fig.transFigure, fancybox=False, edgecolor="k")
    leg.get_frame().set_linewidth(72./fig.dpi)
    plt.show()
    

    enter image description here

    a b (a) (b)