2012-08-16 58 views
53

自從升級matplotlib我得到每當試圖創造一個傳奇以下錯誤:Matplotlib傳奇不工作

import matplotlib.pyplot as plt 

a = [1,2,3] 
b = [4,5,6] 
c = [7,8,9] 

plot1 = plt.plot(a,b) 
plot2 = plt.plot(a,c) 

plt.legend([plot1,plot2],["plot 1", "plot 2"]) 
plt.show() 

我有:

/usr/lib/pymodules/python2.7/matplotlib/legend.py:610: UserWarning: Legend does not support [<matplotlib.lines.Line2D object at 0x3a30810>] 
Use proxy artist instead. 

http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist 

    warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n" % (str(orig_handle),)) 
/usr/lib/pymodules/python2.7/matplotlib/legend.py:610: UserWarning: Legend does not support [<matplotlib.lines.Line2D object at 0x3a30990>] 
Use proxy artist instead. 

http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist 

    warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n" % (str(orig_handle),)) 

這甚至有這樣一個簡單的腳本發生發現錯誤指向的鏈接在診斷錯誤來源時非常沒用。

回答

107

您應該添加逗號:

plot1, = plt.plot(a,b) 
plot2, = plt.plot(a,c) 

您需要的逗號的原因是plt.plot()返回行對象的元組無論有多少實際上是從命令創建的。如果沒有逗號,「plot1」和「plot2」就是元組而不是線對象,從而導致後續對plt.legend()的調用失敗。

逗號隱式地解包結果,以便代替「tuple」,「plot1」和「plot2」自動成爲元組中第一個對象,即您實際需要的線對象。

http://matplotlib.sourceforge.net/users/legend_guide.html#adjusting-the-order-of-legend-items

line, = plot(x,sin(x)) what does comma stand for?

+7

這工作,很神祕的東西! – 2012-08-16 08:28:08

+2

你可以在這裏複製/添加解釋嗎? stackoverflow鼓勵現場複製相關部分(突出顯示,歸檔) – n611x007 2013-11-06 21:39:00

5

使用handles AKA Proxy artists

import matplotlib.lines as mlines 
import matplotlib.pyplot as plt 

blue_line = mlines.Line2D([], [], color='blue', label='My Label') 
reds_line = mlines.Line2D([], [], color='reds', label='My Othes') 

plt.legend(handles=[blue_line, reds_line]) 

plt.show() 
0

使用 「標籤」 的關鍵字,比如:

pyplot.plot(x, y, label='x vs. y') 

然後添加傳說像這樣:

pyplot.legend() 

傳說將保留般粗細,顏色線條屬性等

enter image description here