【问题标题】:Main figure legend outside of subplots次要情节之外的主要人物图例
【发布时间】:2019-09-30 13:08:03
【问题描述】:

我在一个图中有许多子图。每个图都绘制了多条线,它们代表相同的事物(用颜色表示)但在不同的情况下(不同的子图)。我想在图的底部创建一个图例,显示线条颜色的含义。但是,我遇到了让图例不与子图重叠的问题,如果我可以调整轴,让图例保存。

我在here 的帮助下尝试了几种不同的解决方案,但无法适应子图。下面是我正在使用的示例代码。

import numpy as np
import matplotlib.pyplot as plt

m1=1
m2=10

x=np.linspace(0,100,num=101,endpoint=True)
y1m1=m1*x**2
y2m1=m1*x**0.5
y1m2=m2*x**2
y2m2=m2*x**0.5

fig=plt.figure(figsize=(4,4))
ax1=fig.add_subplot(211)
ax1.plot(x,y1m1,'b',label=r'$x^2$')
ax1.plot(x,y2m1,'r',label=r'$\sqrt{x}$')
ax2=fig.add_subplot(212)
ax2.plot(x,y1m2,'b')
ax2.plot(x,y2m2,'r')
fig.legend(loc='lower center',ncol=2)
fig.tight_layout()
fig.savefig('examplefig.png',dpi=300)
plt.show()

我的目标是将输出保存为 png 以获得好图。

【问题讨论】:

    标签: python-3.x matplotlib legend


    【解决方案1】:

    这是使用here 提供的建议的一种方法。这个想法是在相对于给定轴对象的位置添加图例。在您的情况下,由于您想在底部添加图例,因此最好指定相对于ax2 的位置。使用ncol=2 是个人选择的问题。

    fig=plt.figure(figsize=(4,4))
    ax1=fig.add_subplot(211)
    l1, = ax1.plot(x,y1m1,'b')
    l2, = ax1.plot(x,y2m1,'r')
    ax2=fig.add_subplot(212)
    ax2.plot(x,y1m2, 'b')
    ax2.plot(x,y2m2, 'r')
    
    ax2.legend(handles = [l1,l2] , labels=[r'$x^2$', r'$\sqrt{x}$'],
               bbox_to_anchor=(0.7, -0.2), ncol=2)
    
    fig.tight_layout()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-25
      • 2014-09-11
      相关资源
      最近更新 更多