使用Matplotlib在图上写入数值

Cha*_*net 38 python matplotlib

使用Matplotlib,是否可以打印图表上每个点的值?

例如,如果我有:

x = numpy.range(0,10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])
pyplot.plot(x,y)
Run Code Online (Sandbox Code Playgroud)

如何在绘图上显示y值(例如,在(0,5)点附近打印5,在(1,3)点附近打印3等)?

Ste*_*rry 52

您可以使用annotate命令将文本注释放在所需的任何x和y值上.要将它们精确地放在数据点上,您可以执行此操作

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

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

如果您希望注释偏移一点,您可以将annotate行更改为类似的

ax.annotate(str(j),xy=(i,j+0.5))
Run Code Online (Sandbox Code Playgroud)

  • +1正如旁注所示,注释内置了"略微偏离注释".只是做`ax.annotate(STR(j)中,XY =(I,J),xytext =(10,10),textcoords = '偏移指向')`通过在x和y方向10 _points_抵消注释.这通常比数据坐标中的偏移更有用(尽管这也是一种选择). (13认同)

Mar*_*n W 14

使用 pylot.text()

x=[1,2,3]
y=[9,8,7]

pyplot.plot(x,y)
for a,b in zip(x, y): 
    pyplot.text(a, b, str(b))
pyplot.show()
Run Code Online (Sandbox Code Playgroud)