【问题标题】:Python: Combined Legend for Matplotlib SubplotPython:Matplotlib 子图的组合图例
【发布时间】:2018-02-27 04:21:05
【问题描述】:

我正在尝试在 Jupiter Notebook 中创建一个组合图例。当我从示例中尝试各种代码时,我得到一个空的图例。复制的示例可以正常工作,但是当我将其实现到自己的代码中时出现问题。有任何想法吗? 结果:
代码:

fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(15,10))
l1 = ax1.plot(time[18206:18226],tpm2[18206:18226], 'r', label='Chilbolton 2')
ax1.set_title('Difference in Hydrometeor Count Per Minute Over Time')
ax1.set_ylim([0,14000])
ax1.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)

l2 = ax2.plot(time[18206:18226],tpm1[18206:18226], 'b', label='Chilbolton 2')
ax2.set_ylim([0,14000])
ax2.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)

l3 = ax3.plot(time[18206:18226],diff[18206:18226], 'k', label='D.P.M.')
ax3.plot(time[18206:18226],np.zeros(20),'k--')
ax3.set_xlabel('Time (10th February to 29th April)')
ax3.set_ylim([-3000,3000])
ax3.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)

#plt.legend( handles=[l1, l2, l3], labels=['l1','l2','l3'],loc="upper left", bbox_to_anchor=[0, 1],
#           ncol=2, shadow=True, title="Legend", fancybox=True)
fig.legend((l1, l2, l3), ('Line 1', 'Line 2', 'Line 3'), 'upper left')
# ('Chilbolton 2','Chilbolton 2','D.P.M.'), loc = (0.5, 0), ncol=1 )

plt.ylabel('Hydrometeor Count (#)')
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
#f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[-1:]], rotation=90, visible=True)
plt.show()

【问题讨论】:

    标签: python matplotlib legend subplot


    【解决方案1】:

    ax.plot() 返回线条艺术家的列表,即使您只绘制一条线条。所以当你写l1 = ax1.plot(...)时,一个长度为1的列表被分配给l1l2l3 同上。这会导致 fig.legend() 出现问题,它只需要线条艺术家对象。

    您可以通过多种方式解决此问题。最常用的方法是这样的语法:

    l1, = ax1.plot(...
    

    插入逗号会将返回列表的唯一元素分配给l1。你也可以l1 = ax1.plot(...)[0]。或者,在您的情况下,您可以将您的图例调用修改为 fig.legend((l1[0],l2[0],l3[0]),...)

    所以,

    import maptlotlib.pyplot as plt
    
    fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(15,10))
    
    l1, = ax1.plot([0,1],[0,14000])
    ax1.set_title('Difference in Hydrometeor Count Per Minute Over Time')
    ax1.set_ylim([0,14000])
    ax1.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)
    
    l2, = ax2.plot([0,1],[0,14000])
    ax2.set_ylim([0,14000])
    ax2.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)
    
    l3, = ax3.plot([0,1],[-3000,3000])
    ax3.plot(time[18206:18226],np.zeros(20),'k--')
    ax3.set_xlabel('Time (10th February to 29th April)')
    ax3.set_ylim([-3000,3000])
    ax3.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)
    
    fig.legend((l1, l2, l3), ('Line 1', 'Line 2', 'Line 3'), 'upper left')
    

    【讨论】:

      【解决方案2】:

      作为一种解决方法,您可以使用Patch 创建自己的自定义图例:

      import numpy as np            
      import matplotlib.pyplot as plt
      import matplotlib.patches as mpatches
      import random
      
      tx = range(20)
      t1 = np.random.randint(0, 14000, 20)
      t2 = np.random.randint(0, 14000, 20)
      t3 = np.random.randint(-3000, 3000, 20)
      
      labels = ['Chilbolton 2', 'Chilbolton 2', 'D.P.M.']
      
      fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(15,10))
      l1 = ax1.plot(tx, t1, 'r', label=labels[0])
      ax1.set_title('Difference in Hydrometeor Count Per Minute Over Time')
      ax1.set_ylim([0,14000])
      ax1.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)
      
      l2 = ax2.plot(tx,t2, 'b', label=labels[1])
      ax2.set_ylim([0,14000])
      ax2.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)
      
      l3 = ax3.plot(tx,t3, 'k', label=labels[2])
      ax3.plot(tx,np.zeros(20),'k--')
      ax3.set_xlabel('Time (10th February to 29th April)')
      ax3.set_ylim([-3000,3000])
      ax3.grid(b=True, which='major', color='k', linestyle='--', alpha=0.5)
      
      # Create custom legend
      leg1 = mpatches.Patch(color='r')
      leg2 = mpatches.Patch(color='b')
      leg3 = mpatches.Patch(color='k')
      fig.legend(handles=[leg1, leg2, leg3], labels=labels, loc="upper left")
      
      plt.ylabel('Hydrometeor Count (#)')
      # Fine-tune figure; make subplots close to each other and hide x ticks for
      # all but bottom plot.
      #f.subplots_adjust(hspace=0)
      plt.setp([a.get_xticklabels() for a in fig.axes[-1:]], rotation=90, visible=True)
      plt.show()
      

      给你:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-23
        • 1970-01-01
        • 1970-01-01
        • 2017-05-17
        • 1970-01-01
        • 2022-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多