Voici mon code:
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
Je cherche à générer un graphique à bulles avec une légende pour cela, mais d'une certaine manière, il ne montre pas la légende comme il le suppose, juste le graphique, puis affiche ce message.
`TypeError: 'int' object is not iterable`
Qu'est-ce que je fais mal?
1 réponse
Vous ne pouvez pas avoir handles=1
dans plt.legend(handles=1,loc=(2,0))
.
handles
doit être un conteneur, tel qu'une liste, un tuple, etc ...
Non seulement cela, mais un conteneur d'entiers inacceptable. N'écrivez pas handles=[1, 2, 3]
Le code suivant montre comment appeler correctement la méthode 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()
De nouvelles questions
python
Python est un langage de programmation multi-paradigme, typé dynamiquement et polyvalent. Il est conçu pour être rapide à apprendre, comprendre, utiliser et appliquer une syntaxe propre et uniforme. Veuillez noter que Python 2 est officiellement hors support à partir du 01-01-2020. Néanmoins, pour les questions Python spécifiques à la version, ajoutez la balise [python-2.7] ou [python-3.x]. Lorsque vous utilisez une variante Python (par exemple, Jython, PyPy) ou une bibliothèque (par exemple, Pandas et NumPy), veuillez l'inclure dans les balises.