0

I have a function in the form of ax^2+bxy+cy^2+d=0. This one can be written as f(x,y) = 0. I tried to write a code to plot the function in the x,y-plane as follows

import matplotlib.pyplot as plt
import numpy as np

def f(x,y):
    return 0.01*x**2+0.008*x*y-0.013*y**2+0.15*x+0.003*y+1.0097

x = np.arange(-10.0,10.0,0.1)
y = np.arange(-10.0,10.0,0.1)
plt.plot(x, f(x, y));

wrong graph

But I only got a 1D graph of my function. I want the graph where f(x,y) takes the value 0.

Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32
Hermi
  • 357
  • 1
  • 11

1 Answers1

0

To use your function with 2D coordinates you can evaluate it with a grid of x and y values created with np.meshgrid. To draw the graph as a 2D function you can use plt.contour and set the levels to the function value you are interested in

import numpy as np
import matplotlib.pyplot as plt

def f(x,y):
    return 0.01*x**2+0.008*x*y-0.013*y**2+0.15*x+0.003*y+1.0097

x = np.arange(-10.0,10.0,0.1)
y = np.arange(-10.0,10.0,0.1)
X, Y = np.meshgrid(x,y)
plt.contour(x, y, f(X, Y), [0]);

Output

f(x)

Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32
  • Thanks. But why your graph is different from mine? – Hermi Sep 19 '21 at 20:45
  • Can I ask what does parameter '[0]' mean in 'plt.contour(x, y, f(X, Y), [0])'? – Hermi Sep 20 '21 at 08:10
  • 1
    It's the parameter `levels=[0]` *If array-like, draw contour lines at the specified levels. The values must be in increasing order.* from `plt.contour`[documentation](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.contour.html) – Michael Szczesny Sep 20 '21 at 09:54
  • Can I ask how to add a label for this curve in `plt.contour'? Like using `plt.legend()` Thanks. – Hermi Sep 23 '21 at 04:43
  • For example, `plt.contour(x, y, f(X, Y), [0], label='class 1`)`` – Hermi Sep 23 '21 at 04:48
  • You can add the level label to the contour line with `cs = plt.contour(x, y, f(X, Y), [0]); plt.clabel(cs, fmt='%.1f');`. There is no `label` or `name` parameter for `plt.contour`. Solutions can be found [here](https://stackoverflow.com/questions/10490302/how-do-you-create-a-legend-for-a-contour-plot-in-matplotlib) and [here](https://stackoverflow.com/questions/64523051/legend-is-empty-for-contour-plot-is-this-by-design). – Michael Szczesny Sep 23 '21 at 06:31