Creating labels where line appears in matplotlib figure

Each Answer to this Q is separated by one/two green lines.

I have a figure created in matplotlib (time-series data) over which are a series of


lines. I would like to create labels on the plot that appear close to (probably on the RHS of the line and towards the top of the figure) these vertical lines.

You can use something like


you might have to play around with the x and y value in text to get it to align properly.
You can find the more complete documentation here.

A solution without manual placement is to use “blended transformations”.

Transformations transform coordinates from one coordinate system to another. By specifying a transformation through the transform parameter of text, you can give the x and y coordinates of the text in the axis coordinate system (going from 0 to 1 from left to right/top to bottom of the x/y axes, respectively). With blended transformations, you can used a mixed coordinate system.

This is exactly what you need: you have the x coordinate given by the data and you want to place the text on the y axes somewhere relative to the axis, say in the center. The code to do this looks like this:

import matplotlib.transforms as transforms
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# the x coords of this transformation are data, and the
# y coord are axes
trans = ax.get_xaxis_transform()

x = 10
plt.text(x, .5, 'hello', transform=trans)

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .