pandas 类型错误:将第二个图例添加到绘图时,“PathCollection”对象不可迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39984509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:10:44  来源:igfitidea点击:

TypeError: 'PathCollection' object is not iterable when adding second legend to plot

python-2.7pandasmatplotlib

提问by Stefano Potter

I am making a scatter plot from three separate dataframes and plotting the points as well as the best fit lines. I can accomplish this using this code:

我正在从三个单独的数据框中制作散点图,并绘制点以及最佳拟合线。我可以使用以下代码完成此操作:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

fig=plt.figure()
ax1=fig.add_subplot(111)
ax2=fig.add_subplot(111)
ax3=fig.add_subplot(111)

#create scatter plots from the dataframes
ax1.scatter(ex_x, ex_y, s=10, c='r', label='Fire Exclusion')
ax2.scatter(one_x,one_y, c='b', marker='s',label='One Fire')
ax3.scatter(two_x, two_y, s=10, c='g', marker='^', label='Two Fires')

#plot lines of best fit
ax1.plot(ex_x,ex_results.predict(), color = 'r',label = 'Linear (Fire Exclusion)')
ax2.plot(one_x,one_results.predict(), color = 'b',label = 'Linear (One Fire)')
ax3.plot(two_x,two_results.predict(), color = 'g',label = 'Linear (Two Fires)')

#add legend and axis labels
plt.xlabel('NDVI 2004/07/27')
plt.ylabel('NDVI 2005/07/14')
plt.title('NDVI in 2004 vs. 2005')
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), scatterpoints=1)

which gives me:

这给了我:

enter image description here

在此处输入图片说明

Now I want to add a second legend which will display the r2 for each line. I am attempting to do that like this:

现在我想添加第二个图例,它将显示每行的 r2。我正在尝试这样做:

fig=plt.figure()
ax1=fig.add_subplot(111)
ax2=fig.add_subplot(111)
ax3=fig.add_subplot(111)

scat1,=ax1.scatter(ex_x, ex_y, s=10, c='r', label='Fire Exclusion')
scat2,=ax2.scatter(one_x,one_y, c='b', marker='s',label='One Fire')
scat3,=ax3.scatter(two_x, two_y, s=10, c='g', marker='^', label='Two Fires')

lin1,=ax1.plot(ex_x,ex_results.predict(), color = 'r',label = 'Linear (Fire Exclusion)')
lin2,=ax2.plot(one_x,one_results.predict(), color = 'b',label = 'Linear (One Fire)')
lin3,=ax3.plot(two_x,two_results.predict(), color = 'g',label = 'Linear (Two Fires)')

l1 = plt.legend([scat1, scat2,scat3,lin1,lin2,lin3], ["Fire Exclusion", "One Fire", "Two Fires", "Linear (Fire Exclusion)", "Linear (One Fire)", "Linear (Two Fires)"], loc='upper left', scatterpoints=1)

#get r2 from regression results
r2ex=ex_results.rsquared
r2one=one_results.rsquared
r2two=two_results.rsquared

plt.legend([r2ex, r2one, r2two], ['R2 (Fire Exclusion)', 'R2 (One Fire)', 'R2 (Two Fires)'], loc='lower right')

plt.gca().add_artist(l1)
plt.xlabel('NDVI 2004/07/27')
plt.ylabel('NDVI 2005/07/14')
plt.title('NDVI in 2004 vs. 2005')

but this returns:

但这会返回:

Traceback (most recent call last):

  File "<ipython-input-32-b6277bf27ded>", line 1, in <module>
    runfile('E:/prelim_codes/Fire.py', wdir='E:/prelim_codes')

  File "C:\Users\Stefano\Anaconda2_2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
    execfile(filename, namespace)

  File "C:\Users\Stefano\Anaconda2_2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "E:/prelim_codes/Fire.py", line 539, in <module>
    scat1,=ax1.scatter(ex_x, ex_y, s=10, c='r', label='Fire Exclusion')

TypeError: 'PathCollection' object is not iterable

回答by j sad

I had the same error. I found out that you shouldn't include the comma after your variable names. So try

我有同样的错误。我发现您不应该在变量名后包含逗号。所以试试

scat1 =ax1.scatter(ex_x, ex_y, s=10, c='r', label='Fire Exclusion')
scat2 =ax2.scatter(one_x,one_y, c='b', marker='s',label='One Fire')
scat3 =ax3.scatter(two_x, two_y, s=10, c='g', marker='^', label='Two Fires')

instead of

代替

scat1,=ax1.scatter(ex_x, ex_y, s=10, c='r', label='Fire Exclusion')
scat2,=ax2.scatter(one_x,one_y, c='b', marker='s',label='One Fire')
scat3,=ax3.scatter(two_x, two_y, s=10, c='g', marker='^', label='Two Fires')

This is because axes.scatterreturns a PathCollection unlike axes.plot which returns a tuple of the lines plotted (see http://matplotlib.org/1.3.1/users/pyplot_tutorial.html#controlling-line-propertiesand Python code. Is it comma operator?).

这是因为axes.scatter返回一个PathCollection,与axes.plot 不同,后者返回绘制的线的元组(参见http://matplotlib.org/1.3.1/users/pyplot_tutorial.html#controlling-line-propertiesPython 代码。是逗号运算符吗?)。

So for your lines you will still need the comma because you are unpacking the tuple but for the scatter you should not have the comma.

因此,对于您的行,您仍然需要逗号,因为您正在解包元组,但对于散点图,您不应该使用逗号。