1

How is it possible to draw a quadratic bi-variate expression in Python? For example, the following expression:

-0.5x^2 - 0.5y^2 +0.5 xy + x + y + 0.3 = 0 

Is it necessary to convert it to Polar system?

1 Answers1

2

Here is an approach using sympy, Python's symbolic math library:

from sympy import symbols, Eq
from sympy.plotting import plot_implicit

x, y = symbols('x y')
plot_implicit(Eq(-0.5*x**2 - 0.5*y**2 + 0.5*x*y + x + y + 0.3, 0))

plot_implicit

Using numpy and matplotlib, you can create a grid of coordinates and call plt.contour with a contour level of 0:

import matplotlib.pyplot as plt
import numpy as np

x1d = np.linspace(-1, 5, 50)
y1d = np.linspace(-1, 5, 50)
x, y = np.meshgrid(x1d, y1d)
f = -0.5 * x ** 2 - 0.5 * y ** 2 + 0.5 * x * y + x + y + 0.3
fig, ax = plt.subplots()
ax.contour(x, y, f, levels=[0], colors='dodgerblue')
ax.scatter(x=[0.24881, 3.75119], y=[0.24881, 3.75119], color='crimson') # draw two points in matplotlib
ax.set_aspect('equal')
plt.show()

example plot

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • Thank you so much. How is it possible to add some points within this figure? And, also specify x and y ranges – Katan Katalan Mar 11 '21 at 07:02
  • 1
    Sympy's plotting is rather limited in graphical capabilities. You could draw little circles to indicate points. Although internally using matplotlib, it is rather involved to invoke matplotlib functions. A different approach is [to draw everything directly the matplotlib way](https://stackoverflow.com/questions/2484527/is-it-possible-to-plot-implicit-equations-using-matplotlib). – JohanC Mar 11 '21 at 07:19