如果您想使用 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 值来定位数据标签点,因此它位于 y=0
和 x=30
上自己的小区域。
您需要绘制
i
和 j
的线条,否则您只能绘制 x
或 y
数据标签。
你会得到这样的结果(仅注意标签):
不太理想,还有一些重叠。
立即打印
(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
ax.plot(A,B)
for xy in zip(A, B): # <--
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--
ax.grid()
plt.show()
我遇到了类似的问题,最终得到了这个:
对我来说,这样做的优点是数据和注释不重叠。
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()
也可以用来标记点。
import matplotlib.pyplot as plt
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]
fig, ax = plt.subplots()
ax.plot(A,B)
for x, y in zip(A, B):
ax.text(x, y, f"({x}, {y})", fontsize=8)
您还可以注释某些点或通过有条件注释点来更改标签相对于该点的位置。此外,您可以分配任意标签。
例如,以下代码如果
x>0
则在点的左侧绘制标签,否则在右侧绘制标签。此外,annotate()
承认额外的kwargs,可用于美化标签。
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
labels = 'ABCDEFG'
fig, ax = plt.subplots()
ax.plot(A,B)
# annotator function that draws a label and an arrow
# that points from the label to its corresponding point
def annotate(ax, label, x, y, xytext):
ax.annotate(label, xy=(x,y),
xytext=xytext, textcoords='offset points',
fontsize=15,
arrowprops={'arrowstyle': '-|>', 'color': 'black'})
# conditionally position labels
for label, x, y in zip(labels, A, B):
if y > 0.9:
annotate(ax, label, x, y, (-5, -40))
else:
annotate(ax, label, x, y, (-5, 30))