从 Pandas DataFrame 绘图时注释数据点 [英] Annotate data points while plotting from Pandas DataFrame

查看:36
本文介绍了从 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆