gpt4 book ai didi

python - matplotlib.pyplot.legend() 出现类型错误 : zip argument #2 must support iteration,

转载 作者:行者123 更新时间:2023-11-30 22:39:00 24 4
gpt4 key购买 nike

有多种方法可以使用 matplotlib 制作图例。可能更简单的方法是:

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

如果我想完全使用第二种方式,只有一条曲线...我该怎么做?

最佳答案

我相信这样做的原因是定义一个单项元组,您将使用语法(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()

关于python - matplotlib.pyplot.legend() 出现类型错误 : zip argument #2 must support iteration,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43326938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com