2017-04-10 44 views
0

有幾種方法可以用matplotlib製作圖例。可能是更簡單的方法可能是:TypeError:zip參數#2必須支持迭代,使用matplotlib.pyplot.legend()

>>> line_up, = plt.plot([1,2,3], label='Up') 
>>> line_down, = plt.plot([3,2,1], label='Down') 
>>> plt.legend() 
<matplotlib.legend.Legend object at 0x7f527f10ca58> 
>>> plt.show() 

另一種方式可以是:

>>> line_up, = plt.plot([1,2,3]) 
>>> line_down, = plt.plot([3,2,1]) 
>>> plt.legend((line_up, line_down), ('Up', 'Down')) 
<matplotlib.legend.Legend object at 0x7f527eea92e8> 
>>> plt.show() 

這最後的辦法似乎只能使用對象支持迭代工作:

>>> line_up, = plt.plot([1,2,3]) 
>>> plt.legend((line_up), ('Up')) 
/usr/lib64/python3.4/site-packages/matplotlib/cbook.py:137: MatplotlibDeprecationWarning: The "loc" positional argument to legend is deprecated. Please use the "loc" keyword instead. 
    warnings.warn(message, mplDeprecation, stacklevel=1) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib64/python3.4/site-packages/matplotlib/pyplot.py", line 3519, in legend 
    ret = gca().legend(*args, **kwargs) 
    File "/usr/lib64/python3.4/site-packages/matplotlib/axes/_axes.py", line 496, in legend 
    in zip(self._get_legend_handles(handlers), labels)] 
TypeError: zip argument #2 must support iteration 

如果我想只用一條曲線絕對使用第二種方式......我能做什麼?

回答

1

我相信這個原因是定義一個項目元組,你會使用語法(line_up,)。請注意尾部的逗號。

import matplotlib.pyplot as plt 
line_up, = plt.plot([1,2,3]) 
plt.legend((line_up,), ('Up',)) 
plt.show() 

如果您不想包含尾隨逗號,也可以使用列表。例如:

import matplotlib.pyplot as plt 
line_up, = plt.plot([1,2,3], label='my graph') 
plt.legend(handles=[line_up]) 
plt.show() 
+0

太好了!非常感謝,這正是我期待的!我很慚愧,我沒有找到自己......: - (( – servoz

相關問題