87

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

matplotlib.pyplot.axvline

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.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
tripkane
  • 909
  • 2
  • 8
  • 6

2 Answers2

121

You can use something like

plt.axvline(10)
plt.text(10.1,0,'blah',rotation=90)

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.

Dan
  • 12,857
  • 7
  • 40
  • 57
  • 5
    If you want to use data coordinates for the x-axis and axis coordinates for the y-axis, you can place the text at x=10.1 and at 50% of the height using: `ax.text(10.1, 0.5, 'blah', rotation=90, transform=ax.get_xaxis_text1_transform(0)[0])` – Maximilian Mordig Apr 02 '21 at 09:47
  • Link is outdated. – zabop Apr 20 '21 at 19:12
  • If you get a "image size of … pixels is too large" error, check that your coordinates are within the y axis range (https://stackoverflow.com/a/52376517/812102). – Skippy le Grand Gourou Jul 24 '23 at 09:04
31

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
ax.axvline(x)
plt.text(x, .5, 'hello', transform=trans)

plt.show()
Matt Ryall
  • 9,977
  • 5
  • 24
  • 20
ingomueller.net
  • 4,097
  • 2
  • 36
  • 33