在图上标记python数据点

ash*_*ley 68 python annotate matplotlib labels

我搜索了几年(小时,就像年龄)找到一个非常讨厌(看似基本)问题的答案,因为我找不到一个非常适合答案的问题,我发布一个问题并回答它,希望它我将花费大量时间用于我的noobie绘图技巧.

如果你想使用python matplotlib标记你的绘图点

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = anyarray
B = anyotherarray

plt.plot(A,B)
for i,j in zip(A,B):
    ax.annotate('%s)' %j, xy=(i,j), xytext=(30,0), textcoords='offset points')
    ax.annotate('(%s,' %i, xy=(i,j))

plt.grid()
plt.show()
Run Code Online (Sandbox Code Playgroud)

我知道xytext =(30,0)与textcoords一起使用,你使用那些30,0值来定位数据标签点,所以它在0 y轴上,30在x轴上超过它自己的小区域.

您需要绘制i和j的两条线,否则您只绘制x或y数据标签.

你得到这样的东西(仅注意标签):
我自己的情节,标有数据点

它不理想,仍然有一些重叠 - 但它比我所拥有的更好.

fal*_*tru 84

如何立即打印(x, y).

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

plt.grid()
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 对于任何使用此功能的人来说只是一个注意事项:textcoords ='offset points'似乎具有可变效果,具体取决于图形的比例(对我而言,它导致大部分标签出现在图中) (4认同)

Mar*_*hke 7

我有一个类似的问题,最后得到了这个:

在此处输入图片说明

对我来说,这具有数据和注释不重叠的优点。

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()
Run Code Online (Sandbox Code Playgroud)

使用文本参数 in.annotate结束了不利的文本位置。在图例和数据点之间画线是一团糟,因为图例的位置很难定位。