2012-11-09 25 views
38

自定義圖例目前我產生我的傳說與matplotlib這樣:如何使matplotlib

if t==25: 
    l1,l2 = ax2.plot(x320,vTemp320,'or',x320,vAnaTemp320,'-r') 
elif t==50: 
    l3,l4 = ax2.plot(x320,vTemp320,'ob',x320,vAnaTemp320,'-b') 
else: 
    l5,l6 = ax2.plot(x320,vTemp320,'og',x320,vAnaTemp320,'-g') 
plt.legend((l1,l2,l3,l4,l5,l6), ('t=25 Simulation', 't=25 Analytical','t=50 Simulation', 't=50 Analytical','t=500 Simulation', 't=500 Analytical'), 
    bbox_to_anchor=(-.25, 1), loc=2, borderaxespad=0.,prop={'size':12}) 

莫名其妙的作品看1。但是我在我的傳奇中重複了信息。

我寧願分開這個傳說。所以我有不同的顏色線對應於時間t。作爲我的分析解決方案的法線是我模擬結果的點。

類似的東西

- (紅線)T = 25

- (藍線)T = 50

- (綠線)T = 500

Ø模擬論證

- 解析解

有誰現在我怎麼會用matplotlib實現這一點?

The current image

回答

79

你可以選擇藝術家和標籤圖例顯示如下。您需要爲圖例中未實際繪製的元素創建自定義藝術家。

import matplotlib.pyplot as plt 
import numpy as np 

x = np.linspace(0,10,31) 

fig = plt.figure() 
ax = fig.add_subplot(1,1,1) 

#Plot analytic solution 
ax.plot(x,1*x**2, color='r', label="t = 25") 
ax.plot(x,2*x**2, color='b', label="t = 50") 
ax.plot(x,3*x**2, color='g', label="t = 500") 

#Plot simulation 
ax.plot(x,1*x**2, color='r', linestyle='', marker='o') 
ax.plot(x,2*x**2, color='b', linestyle='', marker='o') 
ax.plot(x,3*x**2, color='g', linestyle='', marker='o') 

#Get artists and labels for legend and chose which ones to display 
handles, labels = ax.get_legend_handles_labels() 
display = (0,1,2) 

#Create custom artists 
simArtist = plt.Line2D((0,1),(0,0), color='k', marker='o', linestyle='') 
anyArtist = plt.Line2D((0,1),(0,0), color='k') 

#Create legend from custom artist/label lists 
ax.legend([handle for i,handle in enumerate(handles) if i in display]+[simArtist,anyArtist], 
      [label for i,label in enumerate(labels) if i in display]+['Simulation', 'Analytic']) 

plt.show() 

Example plot

+0

感謝那些完美的作品 – tune2fs

+1

這可能是一個英語的問題,但你所說的「藝術家」是什麼意思? – LWZ

+4

我的意思是matplotlib [artist](http://matplotlib.org/api/artist_api.html)class –