Here's a possible workaround I came up with: suppose I have my intercept coordinates stored as x_intercept
and y_intercept
, and the slope (m) saved as my_slope
which was found through the renowned equation m = (y2-y1)/(x2-x1), or in whichever way you managed to find it.
Using the other famous general equation for a line y = mx + q, I define the function find_second_point
that first computes the q (since m, x and y are known) and then computes another random point that belongs to that line.
Once I have the two points (the initial x_intercept
,y_intercept
and the newly found new_x
,new_y
), I simply plot the segment through those two points. Here's the code:
import numpy as np
import matplotlib.pyplot as plt
x_intercept = 3 # invented x coordinate
y_intercept = 2 # invented y coordinate
my_slope = 1 # invented slope value
def find_second_point(slope,x0,y0):
# this function returns a point which belongs to the line that has the slope
# inserted by the user and that intercepts the point (x0,y0) inserted by the user
q = y0 - (slope*x0) # calculate q
new_x = x0 + 10 # generate random x adding 10 to the intersect x coordinate
new_y = (slope*new_x) + q # calculate new y corresponding to random new_x created
return new_x, new_y # return x and y of new point that belongs to the line
# invoke function to calculate the new point
new_x, new_y = find_second_point(my_slope , x_intercept, y_intercept)
plt.figure(1) # create new figure
plt.plot((x_intercept, new_x),(y_intercept, new_y), c='r', label='Segment')
plt.scatter(x_intercept, y_intercept, c='b', linewidths=3, label='Intercept')
plt.scatter(new_x, new_y, c='g', linewidths=3, label='New Point')
plt.legend() # add legend to image
plt.show()
here is the image generated by the code:
axvline
,axvspan
,axhline
, andaxhspan
, which are similar vertical and horizontal functions, but the usual way in matplotlib is to just plot a line at the given slope (which means that you'll eventually zoom beyond it, if you're working interactively.). The "correct" way of doing it (i.e. so that it's always spans the axis no matter where you zoom) is actually a bit complicated, though the framework (matplotlib.transforms
) is there. – Ihrambase
graphics system for whichabline
exists) so less to worry about there (it's a good and bad thing I suppose). – Pyrophyllite