extending a line segment in matplotlib

• Last Update :
• Techknowledgy :

Have a go to write your own as I don't think this exists in matplotlib. This is a start, you could improve by adding the semiinfinite etc

import matplotlib.pylab as plt
import numpy as np

def extended(ax, x, y, ** args):

xlim = ax.get_xlim()
ylim = ax.get_ylim()

x_ext = np.linspace(xlim[0], xlim[1], 100)
p = np.polyfit(x, y, deg = 1)
y_ext = np.poly1d(p)(x_ext)
ax.plot(x_ext, y_ext, ** args)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
return ax

ax = plt.subplot(111)
ax.scatter(np.linspace(0, 1, 100), np.random.random(100))

x_short = np.linspace(0.2, 0.7)
y_short = 0.2 * x_short

ax = extended(ax, x_short, y_short, color = "r", lw = 2, label = "extended")
ax.plot(x_short, y_short, color = "g", lw = 4, label = "short")

ax.legend()
plt.show()

Adds an infinitely long straight line. The line can be defined either by two points xy1 and xy2

plt.axline(xy1 = (0, 1), xy2 = (1, 0.5), color = 'r')

or defined by one point xy1 and a slope.

plt.axline(xy1 = (0, 1), slope = -0.5, color = 'r')

Sample data for reference:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.default_rng(123).random((2, 100)) * 2 - 1
m, b = -0.5, 1
plt.scatter(x, y, c = np.where(y > m * x + b, 'r', 'k'))

Suggestion : 2

axvline and axhline draw infinite vertical / horizontal lines, at given x / y positions. They are usually used to mark special data values, e.g. in this example the center and limit values of the sigmoid function.,axline can also be used with a transform parameter, which applies to the point, but not to the slope. This can be useful for drawing diagonal grid lines with a fixed slope, which stay in place when the plot limits are moved.,axline draws infinite straight lines in arbitrary directions., Creating a timeline with lines, dates, and text

import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(-10, 10, 100)
sig = 1 / (1 + np.exp(-t))

plt.axhline(y = 0, color = "black", linestyle = "--")
plt.axhline(y = 0.5, color = "black", linestyle = ":")
plt.axhline(y = 1.0, color = "black", linestyle = "--")
plt.axvline(color = "grey")
plt.axline((0, 0.5), slope = 0.25, color = "black", linestyle = (0, (5, 5)))
plt.plot(t, sig, linewidth = 2, label = r "$\sigma(t) = \frac{1}{1 + e^{-t}}$")
plt.xlim(-10, 10)
plt.xlabel("t")
plt.legend(fontsize = 14)
plt.show()
for pos in np.linspace(-2, 1, 10):
plt.axline((pos, 0), slope = 0.5, color = 'k', transform = plt.gca().transAxes)

plt.ylim([0, 1])
plt.xlim([0, 1])
plt.show()

Suggestion : 3

Last Updated : 21 Jun, 2022,GATE CS 2021 Syllabus

Line: 2 3
Line: 1 2
Number of intersection points: 2

Line: 2 3
Line: 1 2
Number of intersection points: 2