python-3.x - 如何使用 pandas 数据框中的列来标记气泡图/散点图?

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

我正在尝试使用 pandas 数据框中的列中的条目来标记从 matplotlib 创建的散点图/气泡图。我见过很多相关的例子和问题(例如 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 datframe 并且不知何故得到了 KeyError - 所以我猜需要一个 dict() 对象?还有其他方法可以使用 pandas 数据框中的条目来标记数据吗?

最佳答案

您可以使用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

关于python-3.x - 如何使用 pandas 数据框中的列来标记气泡图/散点图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41481153/

相关文章:

python-3.x - Python 卡在计算中

python-3.x - 单词不在词汇表中

python - Pandas 按第一列分组并从第二列添加逗号分隔的条目

Python Plot 无法正常工作

Python 和 Pygame 循环不递增

python - 获取 groupby 中的第一个和最后一个值

python - 在具有多索引的 pandas groupby 对象中对日期时间对象使用 diff 时可能出现的错误

python - Groupby Sum 忽略几列

python - matplotlib - 使用 matplotlib 绘制时间序列

python - 以十六进制格式提取 matplotlib 颜色图