Putting text in top left corner of matplotlib plot

You can use text.

plt.text(x, y, s, fontsize=12)

text coordinates can be given relative to the axis, so the position of your text will be independent of the size of the plot:

The default transform specifies that text is in data coords,
alternatively, you can specify text in axis coords (0,0 is lower-left
and 1,1 is upper-right). The example below places text in the center
of the axes::

plt.text(0.5, 0.5, 'matplotlib',
     horizontalalignment="center",
     verticalalignment="center",
     transform = ax.transAxes)

To prevent the text to interfere with any point of your scatter is more difficult afaik. The easier method is to set y_axis (ymax in ylim((ymin,ymax))) to a value a bit higher than the max y-coordinate of your points. In this way you will always have this free space for the text.

EDIT: here you have an example:

from matplotlib import pyplot as plt

f, ax = plt.subplots()
plt.scatter([3,5,2,6,8],[5,3,2,1,5])
plt.text(.01, .99, 'matplotlib', ha="left", va="top", transform=ax.transAxes)
f.tight_layout()

plot

The ha and va parameters set the alignment of your text relative to the insertion point. ie. ha="left" is a good set to prevent a long text to go out of the left axis when the frame is reduced (made narrower) manually.

Leave a Comment