Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plot 2d lines by line equation in Python using Matplotlib

Lets say I have 2d line equations (y = Ax + B) , i.e:

[[A_1, B_1] , [A_2, B_2],  .. ]

and I want to plot the lines in 2d range, for example from point (-100,-100) to point (100,100).

as I understand the range limit can achieved with xlim and ylim, but I don't understand how to draw line according to its equation. I know that one way could be to find 2 points according the equation, but I don't understand how plot function works for my problem, Thanks.

like image 554
Guy P Avatar asked Oct 01 '16 09:10

Guy P


People also ask

How do you draw a line equation in matplotlib?

Matplotlib: Graph/Plot a Straight Line The equation y=mx+c y = m x + c represents a straight line graphically, where m is its slope/gradient and c its intercept.

How do I plot a line in Python matplotlib?

To plot a line plot in Matplotlib, you use the generic plot() function from the PyPlot instance. There's no specific lineplot() function - the generic one automatically plots using lines or markers. This results in much the same line plot as before, as the values of x are inferred.


1 Answers

To plot two straight lines within some specified range in x and y, you would do something like this:

import numpy as np 
import matplotlib.pyplot as plt

A1,B1 = 1.,1.
A2,B2 = 2.,2.

x = np.linspace(-100.,100.)

fig,ax = plt.subplots()
ax.plot(x,A1*x+B1)
ax.plot(x,A2*x+B2)

ax.set_xlim((-100.,100.))
ax.set_ylim((-100.,100.))

plt.show()

Given that you phrased the question in terms of [[A_1, B_1] , [A_2, B_2], .. ], suggesting an array of different lines you'd like to plot, then you can plot using a for loop like this:

import numpy as np 
import matplotlib.pyplot as plt

AB = np.random.randn(100,2) #create a random array of [[A1,B1],[A2,B2],...] as example

x = np.linspace(-100.,100.)

fig,ax = plt.subplots()
for ABi in AB:
    A,B = ABi
    ax.plot(x, A*x+B )

ax.set_xlim((-100.,100.))
ax.set_ylim((-100.,100.))

plt.show()
like image 124
Angus Williams Avatar answered Nov 15 '22 00:11

Angus Williams