65

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.)?

0

3 Answers 3

97

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))
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Just as a side note, annotate has "offseting the annotations a little" built-in. Just do ax.annotate(str(j), xy=(i,j), xytext=(10,10), textcoords='offset points') to offset the annotations by 10 points in the x and y directions. This is often more useful than offsetting in data coordinates (though that's also an option).
33

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

1 Comment

When I use this, it shrinks my graph a lot, do you know why?
2

Current way of displaying values on the bar graph using plt.text() would be

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

hope that helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.