Rac*_*hel 7 matplotlib scatter-plot python-3.x pandas
我试图标记我从matplotlib创建的散点图/气泡图,其中包含pandas数据框中列的条目.我见过很多相关的例子和问题(参见例如此处和此处).因此我试图相应地注释情节.这是我做的:
import matplotlib.pyplot as plt
import pandas as pd
#example data frame
x = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30]
y = [100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600]
s = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30]
users =['mark', 'mark', 'mark', 'rachel', 'rachel', 'rachel', 'jeff', 'jeff', 'jeff', 'lauren', 'lauren', 'lauren']
df = pd.DataFrame(dict(x=x, y=y, users=users)
#my attempt to plot things
plt.scatter(x_axis, y_axis, s=area, alpha=0.5)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.annotate(df.users, xy=(x,y))
plt.show()
Run Code Online (Sandbox Code Playgroud)
我使用了一个pandas数据帧,但我得到了一个KeyError-所以我想一个dict()对象是预期的?有没有其他方法使用pandas数据框中的条目标记数据?
您可以使用DataFrame.plot.scatter然后选择in循环DataFrame.iat:
ax = df.plot.scatter(x='x', y='y', alpha=0.5)
for i, txt in enumerate(df.users):
ax.annotate(txt, (df.x.iat[i],df.y.iat[i]))
plt.show()
Run Code Online (Sandbox Code Playgroud)
Jezreal 的答案很好,但我发布这个只是为了展示我df.iterrows在其他线程中的意思。
如果您想拥有动态大小,恐怕您还必须将散点(或绘图)命令放入循环中。
df = pd.DataFrame(dict(x=x, y=y, s=s, users=users))
fig, ax = plt.subplots(facecolor='w')
for key, row in df.iterrows():
ax.scatter(row['x'], row['y'], s=row['s']*5, alpha=.5)
ax.annotate(row['users'], xy=(row['x'], row['y']))
Run Code Online (Sandbox Code Playgroud)