首页 文章

是否可以测试图例是否覆盖了matplotlib / pyplot中的任何数据

提问于
浏览
3

Python初学者如果在任何时候都有不正确的术语,请道歉 .

我正在使用 legend(loc='best', ...) 方法,它可以在99%的时间内工作 . 但是,当在单个图形上堆叠超过9个图(即,在下面的示例中为i> 9)时,使用单个标签时,它默认为居中并覆盖数据 .

有没有办法在脚本中运行测试,如果图例覆盖任何数据点,它将给出真/假值?

非常简化的代码:

fig = plt.figure()
    for i in data:
        plt.plot(i[x, y], label=LABEL)
fig.legend(loc='best')
fig.savefig()

Example of legend covering data

1 回答

  • 1

    一种方法是在轴的底部/顶部/左侧或右侧添加一些额外的空间(在您的情况下,我更喜欢顶部或底部),通过稍微改变限制 . 这样做可以使图例适合数据 . 通过使用 ax.set_ylim(-3e-4, 1.5e-4) 设置不同的y限制来添加额外空间(上限大约是图中的值,-3是您需要的估计值) .

    您还需要做的是在创建图例时将图例添加到更多列中,并使用关键字 ncol=N .

    Figure

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.figure()
    
    ax = fig.add_subplot(111)
    
    x = np.linspace(0, 1, 100)
    y = 3.5 * x - 2
    for i in range(9):
        ax.plot(x, y + i / 10., label='iiiiiiiiiiii={}'.format(i))
    
    ax.set_ylim(-3, 1.5)
    ax.legend(loc='lower center', ncol=3)  # ncol=3 looked nice for me, maybe you need to change this
    plt.show()
    

    EDIT

    另一个解决方案是将图例放在一个单独的轴上,就像我在下面的代码中所做的那样 . 数据图不需要关心为图例或任何东西创建空间,并且您应该在下面的轴中有足够的空间来放置所有的行标签 . 如果需要更多空间,可以轻松更改上轴与下轴的比率 .

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.figure()
    
    ax = fig.add_subplot(211)
    ax_leg = fig.add_subplot(212)
    
    x = np.linspace(0, 1, 100)
    y = 3.5 * x - 2
    lines = []
    for i in range(9):  #for plotting the actual data
        li, = ax.plot(x, y + i / 10., label='iiiiiiiiiiii={}'.format(i))
        lines.append(li)
    
    for line in lines:  # just to make the legend plot
        ax_leg.plot([], [], line.get_color(), label=line.get_label())
    ax_leg.legend(loc='center', ncol=3, )  # ncol=3 looked nice for me, maybe you need to change this
    ax_leg.axis('off')
    fig.show()
    

    enter image description here

相关问题