从Pandas DataFrame绘图时注释数据点 [英] Annotate data points while plotting from Pandas DataFrame
问题描述
我想在数据点旁边标注数据点的值.我发现的示例仅将x和y作为向量处理.但是,我想对包含多个列的pandas DataFrame进行此操作.
I would like to annotate the data points with their values next to the points on the plot. The examples I found only deal with x and y as vectors. However, I would like to do this for a pandas DataFrame that contains multiple columns.
ax = plt.figure().add_subplot(1, 1, 1)
df.plot(ax = ax)
plt.show()
为多列DataFrame注释所有点的最佳方法是什么?
What is the best way to annotate all the points for a multi-column DataFrame?
推荐答案
是否要使用其他列之一作为注释的文本?这是我最近所做的.
Do you want to use one of the other columns as the text of the annotation? This is something I did recently.
从一些示例数据开始
In [1]: df
Out[1]:
x y val
0 -1.015235 0.840049 a
1 -0.427016 0.880745 b
2 0.744470 -0.401485 c
3 1.334952 -0.708141 d
4 0.127634 -1.335107 e
绘制点.在此示例中,我将y与x作图.
Plot the points. I plot y against x, in this example.
ax = df.set_index('x')['y'].plot(style='o')
编写一个在x,y和值上循环的函数,以便在该点旁边进行注释.
Write a function that loops over x, y, and the value to annotate beside the point.
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['val']))
label_point(df.x, df.y, df.val, ax)
draw()
这篇关于从Pandas DataFrame绘图时注释数据点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!