How can I use matplotlib to plot the function max{abs(x1),abs(x2)} <= 1 ? The graph should be like this enter image description here
I have really no idea.
How can I use matplotlib to plot the function max{abs(x1),abs(x2)} <= 1 ? The graph should be like this enter image description here
I have really no idea.
A standard way to plot an implicit function uses:
np.meshgrid
z
of x
and y
, e.g. z = x**2 + y**2
plt.contourf()
between two levels, e.g. between minus infinity and 1, to show the areaplt.contour()
with one level to draw one or more curves to indicate that levelimport matplotlib.pyplot as plt
import numpy as np
x, y = np.meshgrid(np.linspace(-2, 2, 100), np.linspace(-2, 2, 100))
z = np.maximum(np.abs(x), np.abs(y))
plt.contourf(x, y, z, levels=[-np.inf, 1], colors=['skyblue'], alpha=0.3)
plt.contour(x, y, z, levels=[1], colors=['skyblue'])
plt.axis('equal') # show squares undeformed
plt.tight_layout()
plt.show()
If you just want a square from -1 to 1 in both axes, then you can do:
import matplotlib.pyplot as plt
x = [-1, -1, 1, 1, -1]
y = [-1, 1, 1, -1, -1]
plt.plot(x, y)