Writing numerical values on the plot with Matplotlib


Question

Is it possible, with Matplotlib, to print the values of each point on the graph?

For example, if I have:

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

How can I display y values on the plot (e.g. print a 5 near the (0,5) point, print a 3 near the (1,3) point, etc.)?

1
35
6/8/2011 4:24:42 PM

Accepted Answer

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

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

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))
47
6/8/2011 5:19:19 PM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon