在图上标记python数据点

时间:2014-03-08 16:41:19

标签: python matplotlib labels annotate

我搜索了几年(几个小时,就像年龄一样)来找到一个非常烦人(看似基本)问题的答案,因为我找不到一个非常适合答案的问题,我发布了一个问题并在答案中回答了问题。希望它能节省别人我花在我的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()

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

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

你得到这样的东西(仅注意标签):
My own plot with data points labeled

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

2 个答案:

答案 0 :(得分:80)

如何一次打印(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()

enter image description here

答案 1 :(得分:0)

我遇到了类似的问题,并最终得出以下结论:

enter image description here

对我来说,这样做的好处是数据和注释不重叠。

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()

.annotate中使用text自变量最终会导致不利的文本位置。 在图例和数据点之间画线是一团糟,因为图例的位置很难确定。

相关问题