python - Python 气泡图 Legands- TypeError
问题描述
这是我的代码:
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`
我究竟做错了什么?
解决方案
你不能handles=1
在plt.legend(handles=1,loc=(2,0))
.
handles
必须是容器,例如列表、元组等...
不仅如此,还有一个不可接受的整数容器。不要写handles=[1, 2, 3]
以下代码显示了如何正确调用该legend
方法:
import numpy as np
import matplotlib.pyplot as plt
# Make some fake data.
a = b = np.arange(0, 3, .02)
c = np.exp(a)
d = c[::-1]
fig, ax = plt.subplots()
line1 = ax.plot(a, c, 'k--')
line2 = ax.plot(a, d, 'k:')
line3 = ax.plot(a, c + d, 'k')
ax.legend((line1, line2, line3), ('line 1', 'line 2', 'line 3'), loc=(2,0))
plt.show()
推荐阅读
- mysql - 如何从另一个表的另一列中插入数据?
- utf-8 - 如何使用热字符串显示重音字符?
- swift - 创建没有后退按钮 SwiftUI 的 NavigationLink
- javascript - 角路由失败 - 模态弹出
- php - 通过 PHP 批量调整图像大小的问题
- azure - Terraform - 创建 Azure 事件网格订阅 - 可以吗?
- c++ - 编译器在尝试使用继承定义类时出错
- laravel - 如何在 Redis 队列中调度延迟(待处理)作业?
- javascript - Azure DevOps 在部署之前更新代码内的变量
- python - Pygame中如何正确继承Surface类