使用Matplotlib在图表上写入数值

64

使用Matplotlib,能否在图表上打印每个点的值?

例如,如果我有以下数据:

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

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

3个回答

94

您可以使用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()

如果你想要注释有一点偏移,你可以将annotate行更改为类似以下的内容

ax.annotate(str(j),xy=(i,j+0.5))

22
作为一个侧面说明,annotate()函数已经内置了调整注释位置的功能。只需使用ax.annotate(str(j), xy=(i,j), xytext=(10,10), textcoords='offset points'),就可以在x和y方向上分别将注释偏移10个点。这往往比在数据坐标系中进行偏移更有用(尽管后者也是一种选项)。 - Joe Kington

32

使用pyplot.text()函数 (import matplotlib.pyplot as plt)。

import matplotlib.pyplot as plt

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

plt.plot(x,y)
for a,b in zip(x, y): 
    plt.text(a, b, str(b))
plt.show()

当我使用这个时,它会使我的图形缩小很多,你知道为什么吗? - Elliptica

0
当前使用plt.text()在条形图上显示数值的方法是:
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = np.array([5,3,4,2,7,5,4,6,3,2])
#for modifying figsize
fig, ax = plt.subplots(figisize=(8,12))
ax.bar(x,y)
for i, j in zip(x,y):
    ax.text(i,j, str(j), ha='center', va='bottom')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

希望有所帮助

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接