The standard code for plotting lines from a point would be something like the following:
import numpy as np
from matplotlib import pyplot as plt
def plot_tangents(x, y, tangents):
plt.plot(x, y, 'b.')
# set xlim/ylim
plt.xlim([min(x)-50, max(x)+50])
plt.ylim([min(y)-50, max(y)+50])
for i, m in enumerate(tangents):
tx = np.linspace(x[i] - 5, x[i] + 5)
plt.plot(tx, m*(tx - x[i]) + y[i], 'r--', label=f"y={m}(x - {x[i]} + {y[i]}")
plt.show()
# Working example
dummyx = np.linspace(50, 100)
dummyy = np.linspace(50, 100)
dummym = np.linspace(1, 1)
plot_tangents(dummyx, dummyy, dummym)
# Failing example
dummyx = np.linspace(50, 50)
dummyy = np.linspace(200, 550)
dummym = np.array([np.inf] * 50)
plot_tangents(dummyx, dummyy, dummym)
However when given vertical lines with linspace in x or horizontal lines with linspace in y, this code will fail to plot.
Is there anyway to get matplot to handle these cases - ideally I'd like to plot a limited segment length for the tangent rather than an x/y range.
Expected tangents forming the line
Missing vertical line, no plot visible (which makes sense from the equation)
Partial Solution
The missing vertical line can be fixed with the following change to the line plot code - thanks @tdy - but understandably this is now an infinite line tangent.
plt.axline(xy1=(x[i], y[i]), slope=m, label=f'$y {-y[i]:+} = {m}(x {-x[i]:+})$')