如何用 pandas 数据框中的列标记气泡 chart/scatter 图?

How to label bubble chart/scatter plot with column from pandas dataframe?

我正在尝试用 pandas 数据框中的列中的条目标记我从 matplotlib 创建的 scatter/bubble 图表。我已经看到很多相关的示例和问题(参见 and here)。因此,我试图相应地注释情节。这是我所做的:

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 datframe 并且我以某种方式得到了一个 KeyError - 所以我想应该是一个 dict() 对象?有没有其他方法可以使用 pandas 数据框中的条目来标记数据?

您可以使用 DataFrame.plot.scatter and then select in loop by 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()

Jezreal 的回答很好,但我 post 这只是为了说明我在另一个线程中 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']))