Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 868
Max Avatar asked Feb 16 '11 20:02

Max


People also ask

How do I insert a horizontal line in Matplotlib?

The axhline() function in pyplot module of matplotlib library is used to add a horizontal line across the axis. Parameters: y: Position on Y axis to plot the line, It accepts integers. xmin and xmax: scalar, optional, default: 0/1.

How do I draw a line in Matplotlib?

You can also plot many lines by adding the points for the x- and y-axis for each line in the same plt. plot() function. (In the examples above we only specified the points on the y-axis, meaning that the points on the x-axis got the the default values (0, 1, 2, 3).)

How do I make a Matplotlib legend outside the plot?

To place the legend outside of the axes bounding box, one may specify a tuple (x0, y0) of axes coordinates of the lower left corner of the legend. places the legend outside the axes, such that the upper left corner of the legend is at position (1.04, 1) in axes coordinates.


1 Answers

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

like image 93
Paul Avatar answered Sep 20 '22 19:09

Paul