簡體   English   中英

Python:Matplotlib子圖的合並圖例

[英]Python: Combined Legend for Matplotlib Subplot

我正在嘗試在木星筆記本中制作一個傳奇。 當我嘗試使用示例中的各種代碼時,會得到一個空的圖例。 這些示例可以很好地復制,但是當我將其實現到自己的代碼中時出了點問題。 有任何想法嗎? 結果:
顯示代碼的結果 碼:

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

即使您僅繪制一條線, ax.plot()返回一個行藝術家列表 因此,當您編寫l1 = ax1.plot(...)l1 = ax1.plot(...)長度為1的列表分配給l1 同上l2l3 這給fig.legend()了一個問題, 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')

在此處輸入圖片說明

解決方法是,您可以使用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()

給你:

演示傳奇

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM