Max
Max

Reputation: 3445

How to draw a line outside of an axis in matplotlib (in figure coordinates)

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.

Upvotes: 22

Views: 21832

Answers (1)

Paul
Paul

Reputation: 43680

  • 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?

Upvotes: 21

Related Questions