20

Matplotlib has a function that writes text in figure coordinates (.figtext())

Is there a way to do the same but for drawing lines?

In particular my goal is to draw lines to group some ticks on the y-axis together.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Max
  • 3,384
  • 2
  • 27
  • 26

1 Answers1

21
  • Tested in python 3.8.12, matplotlib 3.4.3
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

x = np.linspace(0,10,100)
y = np.sin(x)*(1+x)

fig, ax = plt.subplots()
ax.plot(x,y,label='a')

# new clear axis overlay with 0-1 limits
ax2 = plt.axes([0,0,1,1], facecolor=(1,1,1,0))

x,y = np.array([[0.05, 0.1, 0.9], [0.05, 0.5, 0.9]])
line = Line2D(x, y, lw=5., color='r', alpha=0.4)
ax2.add_line(line)

plt.show()

enter image description here

But if you want to align with ticks, then why not use plot coordinates?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Paul
  • 42,322
  • 15
  • 106
  • 123
  • That would be better, but I can't get it to draw outside of the axes. I'd like to draw where the tick labels are. (outside of where the plot is) (I tried what would be basically `ax.add_line(line)` in your above example, but with coordinates that are roughly where the ticks are...) – Max Feb 16 '11 at 23:01
  • 21
    @Max In that case, just set `line.set_clip_on(False)`. Would you like another answer demonstrating this? – Paul Feb 16 '11 at 23:13
  • Thanks. set_clip_on(False) is a great tip. I solved my problem by computing the line locations in figure coordinates, but now I know for the future. No need to write another answer -- thanks again. – Max Feb 17 '11 at 00:03
  • 3
    Instead of doing `ax2.add_line(line)` you can do `fig.add_artist(line)` so you can work on the whole figure instead of just one subplot – raquelhortab Jun 06 '21 at 11:27