如何用 pandas 数据框中的列标记气泡图/散点图? [英] How to label bubble chart/scatter plot with column from pandas dataframe?
问题描述
我正在尝试使用从matplotlib创建的散点图/气泡图来标记熊猫数据框中一列的条目.我已经看到很多相关的示例和问题(请参见例如这里).因此,我尝试相应地注释该情节.这是我的工作:
I am trying to label a scatter/bubble chart I create from matplotlib with entries from a column in a pandas data frame. I have seen plenty of examples and questions related (see e.g. here and here). Hence I tried to annotate the plot accordingly. Here is what I do:
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()
我使用熊猫datframe并以某种方式得到KeyError-,所以我猜应该是dict()
对象?还有其他方法可以将数据与pandas数据框中的条目一起使用吗?
I use a pandas datframe and I somehow get a KeyError- so I guess a dict()
object is expected? Is there any other way to label the data using with entries from a pandas data frame?
推荐答案
您可以使用 DataFrame.iat
:
You can use 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()
这篇关于如何用 pandas 数据框中的列标记气泡图/散点图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!