0

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.

Krischen
  • 9
  • 1
  • What are `x1` and `x2`? Is `x1` meant to be `x`, and `x2` meant to be `y`? – sbottingota Feb 17 '23 at 09:08
  • I think it was not a good idea to mark this question a duplicate of the other one. `max(abs(x1), abs(x2)) <= 1` is not really an implicit equation; it's just a compact way of writing `abs(x1) <= 1 and abs(x2) <= 1`. Just simple linear bounds. A tool for implicit equations wouldn't be the right tool for this. – Stef Feb 17 '23 at 10:12

2 Answers2

1

A standard way to plot an implicit function uses:

  • a fine grid of x and y positions in some range; this grid can be created by np.meshgrid
  • a function 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 area
  • plt.contour() with one level to draw one or more curves to indicate that level
import 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()

plotting an implicit function

JohanC
  • 71,591
  • 8
  • 33
  • 66
0

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)
sbottingota
  • 533
  • 1
  • 3
  • 18