在图上标记 python 数据点

我花了很长时间(相当于很长时间)寻找一个非常烦人(看似基本的)问题的答案,因为我找不到一个非常适合这个答案的问题,所以我发布了一个问题并回答了它,希望它能帮助别人节省我刚刚在菜鸟绘图技巧上花费的大量时间。

如果要使用 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)与文本坐标一致,你使用这些30,0值来定位数据标签点,所以它在0 y 轴上,在 x 轴上的30在它自己的小区域上。

需要同时绘制 i 和 j 的直线,否则只能绘制 x 或 y 数据标签。

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

这并不理想,仍然有一些重叠-但总比什么都没有,这是我有。

198296 次浏览

How about print (x, y) at once.

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


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


ax.grid()
plt.show()

enter image description here

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

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

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.