如何使用pandas dataframe中的列标记气泡图/散点图?

时间:2017-01-05 09:18:54

标签: python-3.x pandas matplotlib scatter-plot

我正在尝试标记我在matplotlib中创建的散点图/气泡图,其中包含pandas数据框中列的条目。我看到了很多相关的示例和问题(例如herehere)。因此我试图相应地注释情节。这是我的工作:

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()

我使用了一个pandas数据帧,但我得到了一个KeyError-所以我想一个dict()对象是预期的?有没有其他方法使用pandas数据框中的条目标记数据?

2 个答案:

答案 0 :(得分:8)

您可以使用DataFrame.plot.scatter然后按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()

graph

答案 1 :(得分:3)

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']))

enter image description here