这是我的代码:
import pandas
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
%matplotlib inline
pandas.set_option ('max_columns',10)
df= pandas.read_csv('C:/Users/HP/Desktop/Coding/Python/2.Python Data Analysis/Module 2- Python Data Visualization/M2-Bubble Chart with Labels and Legend data.csv')
plt.scatter(x=df['GDP per Capita'],y=df['Life Span'],s=df['Population']/1000, alpha=0.5, c=df['Bubble color'])
#alpha at 0.5 to set the transparency
#chart title, axis labels
plt.title('GDP,Lifespan,Population (Bubble size)')
plt.xlabel(' GDP')
plt.ylabel('Lifespan')
#bubble labels
x,y= df['GDP per Capita'],df['Life Span']
for i, txt in enumerate (df['Territory']):
plt.annotate(txt,(x[i],y[i]))
print(i,txt,x[i],y[i],df['Population'][i],df['Bubble color'][i])
#annotate: is used to assign the population with the chart sp have from text, the x and y will be the next one
#it will print out the index number with the one that assigned with it as well
#legend
territory_list=list(df['Territory'])
bubble_color_list = list(df['Bubble color'])
l = []
for i in range (0,len(df.index)):
l.append(mpatches.Patch(color=bubble_color_list[i],
alpha=0.5,
label=territory_list[i]))
plt.legend(handles=1,loc=(2,0))
#the i is in the For loop is just basically like the one above to have all the information
我希望为其生成带有图例的气泡图,但不知何故它不会像预期的那样仅显示图例,然后显示此消息。
`TypeError: 'int' object is not iterable`
我在做什么错了?
答案 0 :(得分:0)
您不能在result = []
for check_list in sl:
if not any(contains_list(check_list, source_list) for source_list in l)
result.append(check_list)
print(result)
中拥有handles=1
。
plt.legend(handles=1,loc=(2,0))
必须是容器,例如列表,元组等...
不仅如此,而且整数容器也是不可接受的。不要写handles
以下代码显示了如何正确调用handles=[1, 2, 3]
方法:
legend