This notebook can be useful to make a graphical representation of linear systems of 2 variables.
In [ ]:
# Init matplotlib
%matplotlib inline
import matplotlib
In [ ]:
FIG_SIZE = 4
def plot_linear_system(Ab, bounds=None, ax=None, color='r', alpha=1):
"""Plot the linear system defined by the extended matrix `Ab`."""
# Check arguments #############
assert Ab.ndim == 2
assert Ab.shape[1] == 3
if bounds is None:
if ax is None:
bounds = np.array([[-10, 10],
[-10, 10]])
else:
bounds = np.array(ax.axis()).reshape([2,2])
assert bounds.ndim == 2
assert bounds.shape == (2, 2)
assert bounds[0,0] < bounds[0,1]
assert bounds[1,0] < bounds[1,1]
# Setup the plot ##############
if ax is None:
fig, ax = plt.subplots(figsize=(FIG_SIZE, FIG_SIZE))
ax.axis('equal')
ax.axis(bounds.flatten())
ax.set_xticks(np.arange(*bounds[0], 1))
ax.set_yticks(np.arange(*bounds[0], 1))
ax.axhline(y=0, color='k')
ax.axvline(x=0, color='k')
# Compute points to plot ######
x = bounds[0] # horizontal axis limits
Abnv = Ab[Ab[:,1] != 0] # linear equations having a non-null x_2 coefficient (i.e. non-vertical line)
Abv = Ab[Ab[:,1] == 0] # linear equations having a null x_2 coefficient (i.e. vertical line)
# Plot non-vertical lines #####
yp1 = (Abnv[:,2] - Abnv[:,0] * x[0]) / Abnv[:,1]
yp2 = (Abnv[:,2] - Abnv[:,0] * x[1]) / Abnv[:,1]
plt.plot(x, np.array([yp1, yp2]), "-{}".format(color), alpha=alpha)
# Plot vertical lines #########
for ab in Abv:
plt.axvline(ab[2] / ab[0], color=color, alpha=alpha)
# TODO: add label (e.g. "2x + 3y = 1")
plt.grid(True)
return ax
In [ ]:
Ab = np.array([[0, 1, 1],
[1, 0, 1],
[1, 1, 2]])
plot_linear_system(Ab);
In [ ]:
Ab = np.array([[-3, 9, 9],
[1, 1, 5]])
bounds = np.array([[-2, 6], [-2, 6]])
plot_linear_system(Ab, bounds=bounds);
Ab = np.array([[-1., 3., 3.],
[-1., 7., 11.]])
Ab[0] = Ab[0] + -0.2 * Ab[1]
print(Ab)
plot_linear_system(Ab, bounds=bounds);
Ab = np.array([[1, 0, 3],
[0, 1, 2]])
plot_linear_system(Ab, bounds=bounds);
In [ ]:
Ab = np.array([[-2, 4, -4],
[ 6, 7, 11]])
ax = plot_linear_system(Ab, bounds=np.array([[-5, 5], [-5, 5]]), alpha=0.5);
Ab = np.array([[-2, 4, -4],
[ 0, 19, -1]])
plot_linear_system(Ab, ax=ax, color='g', alpha=0.5);