looking for marker text option for pyplot.plot()

Rah picture Rah · Dec 20, 2014 · Viewed 10.1k times · Source

I am looking for a way to insert numbers or text into markers. There is nothing in the matplotlib.pyplot.plot(*args, **kwargs) documentation about that.

The default zoom level places markers on the edge, hence reducing the available space on which to inscribe text.

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

Answer

snake_charmer picture snake_charmer · Dec 20, 2014

As jkalden suggested, annotate would solve your problem. The function's xy-argument let you position the text so that you can place it on the marker's position.

About your "zoom" problem, matplotlib will by default stretch the frame between the smallest and largest values you are plotting. It results in your outer markers having their centers on the very edge of the figure, and only half of the markers are visible. To override the default x- and y-limits you can use set_xlim and set_ylim. Here an offset is define to let you control the marginal space.

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

Here is how it looks:

Running the suggested code above gives a figure like this.