我想用x轴值标记pandas中的数据点。我正在尝试将此解决方案应用到我的代码中:Annotate data points while plotting from Pandas DataFrame
我收到一条错误说:
AttributeError: 'PathCollection' object has no attribute 'text'
这是我的代码:
def draw_scatter_plot(xaxis, yaxis, title, xaxis_label, yaxis_label, save_filename, color, figsize=(9, 7), dpi=100):
fig = plt.figure(figsize=figsize, dpi=dpi)
ax = plt.scatter(xaxis, yaxis, c=color)
plt.xlabel(xaxis_label)
plt.ylabel(yaxis_label)
label_point(xaxis, yaxis, xaxis, ax)
plt.title(title)
fig.savefig(save_filename, dpi=100)
# label code from https://stackoverflow.com/questions/15910019/annotate-data-points-while-plotting-from-pandas-dataframe/15911372#15911372
def label_point(x, y, val, ax):
a = pd.concat({'x': x, 'y': y, 'val': val}, axis=1)
for i, point in a.iterrows():
ax.text(point['x'], point['y'], str(point['x']))
有关此问题的任何建议吗?
答案 0 :(得分:3)
考虑以下演示:
In [6]: df = pd.DataFrame(np.random.randint(100, size=(10, 2)), columns=list('xy'))
In [7]: df
Out[7]:
x y
0 44 13
1 69 53
2 52 80
3 72 64
4 66 42
5 96 33
6 31 13
7 61 81
8 98 63
9 21 95
In [8]: ax = df.plot.scatter(x='x', y='y')
In [9]: df.apply(lambda r: ax.annotate(r['x'].astype(str)+'|'+r['y'].astype(str),
(r.x*1.02, r.y*1.02)), axis=1)
Out[9]:
0 Annotation(44,13,'44|13')
1 Annotation(69,53,'69|53')
2 Annotation(52,80,'52|80')
3 Annotation(72,64,'72|64')
4 Annotation(66,42,'66|42')
5 Annotation(96,33,'96|33')
6 Annotation(31,13,'31|13')
7 Annotation(61,81,'61|81')
8 Annotation(98,63,'98|63')
9 Annotation(21,95,'21|95')
dtype: object
结果:
答案 1 :(得分:0)
出现此问题是因为您将plt.scatter
返回名称ax
。这很令人困惑,因为它不是一个轴,而是一个'PathCollection'
(正如错误告诉你的那样)。
替换前两行
fig = plt.figure(figsize=figsize, dpi=dpi)
ax = plt.scatter(xaxis, yaxis, c=color)
通过
fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
ax.scatter(xaxis, yaxis, c=color)
并保持其余代码相同。