My confusion was just based on a typo in my code - nothing interesting to learn here! I simply plotted the wrong function, see my comment to the accepted answer.
Here are some seemingly harmless Python code
import matplotlib.pyplot as plt
import numpy as np
delta = 0.02
x = np.arange(-10, 10, delta)
y = np.arange(-10, 10, delta)
[X, Y] = np.meshgrid(x, y)
fig, ax = plt.subplots()
Z = X**2+2*X*Y+Y**2
# for comparison later use this:
#Z = 3.14*X**2+0.6*Y**2
ax.contour(X, Y, Z)
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.show()
and its output:
The plotted contour lines are wrong! I am doing the contour plot of a quadratic function and the contour lines should be ellipses. The shown lines are not just seemingly lines, which at a bigger scale would become ellipses. I have at least two reasons for saying so:
Here is the Wolfram Alpha contour plot of the same function at a similar scale. It shows the ellipsis that should be there.
I calculated by hand the corresponding diagonal quadratic form (according to the Principal Axis theorem): It is, with a bit of rounding,
Z = 3.14*X**2+0.6*Y**2
.
This a function which first rotates a given vector (X,Y)
by a certain angle and then applies the function Z = X**2+2*X*Y+Y**2
used in the code. Thus the contour plots of the two functions should just differ by a rotation.
But inserting Z = 3.14*X**2+0.6*Y**2
in the above code, in place of the previous Z
, produces a perfectly fine ellipsis:
My questions:
- What is the explanation for his behaviour?
- What can I do to get an accurate contour plot of the first function?