为 pyplot.plot() 寻找标记文本选项

Rah*_*Rah 3 python plot text matplotlib markers

我正在寻找一种将数字或文本插入标记的方法。matplotlib.pyplot.plot(*args, **kwargs)文档中没有关于这一点的内容。

默认缩放级别将标记放置在边缘上,从而减少了用于刻录文本的可用空间。

import matplotlib.pyplot as plt
x = [1, 2, 3, 4 ,5]
y = [1, 4, 9, 6, 10]
plt.plot(x, y, 'ro',markersize=23)
plt.show()
Run Code Online (Sandbox Code Playgroud)

sna*_*mer 6

正如 jkalden 所建议的那样,annotate可以解决您的问题。该函数的xy-argument 可让您定位文本,以便将其放置在标记的位置。

关于您的“缩放”问题,matplotlib默认情况下将在您绘制的最小值和最大值之间拉伸框架。这会导致您的外部标记的中心位于图形的最边缘,并且只有一半的标记可见。要覆盖默认的 x 和 y 限制,您可以使用set_xlimset_ylim。这里定义了一个偏移量,让您控制边缘空间。

import matplotlib.pyplot as plt

x = [1, 2, 3, 4 ,5]
y = [1, 4, 9, 6, 10]

fig, ax = plt.subplots()

# instanciate a figure and ax object
# annotate is a method that belongs to axes
ax.plot(x, y, 'ro',markersize=23)

## controls the extent of the plot.
offset = 1.0 
ax.set_xlim(min(x)-offset, max(x)+ offset)
ax.set_ylim(min(y)-offset, max(y)+ offset)

# loop through each x,y pair
for i,j in zip(x,y):
    corr = -0.05 # adds a little correction to put annotation in marker's centrum
    ax.annotate(str(j),  xy=(i + corr, j + corr))

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

这是它的外观:

运行上面建议的代码给出了这样的图。