I understand that a contour plot shows lines for all points that share a particular value. But when I draw a contour plot in matplotlib
for the square of the sum of x^2 and y^2, the point for (1, 1) -- computes to 1.41 -- lies between the contour lines labeled 1.5 and 2.0.
Shouldn't that point lie between the contour lines for 1.0 and 1.5?
Likewise the point for (0.707, 0.707) -- computes to 1 -- lies on the contour line for 1.5. Shouldn't that point be on the 1.0 contour line?
What am I missing / doing wrong here?
import numpy as np
import matplotlib.pyplot as plt
zval = 1
xval = np.sqrt(zval**2/2)
print(xval) # 0.707
yval = xval
print(yval)
print(np.sqrt(xval**2 + yval**2)) # 1
xlist = np.linspace(-3.0, 3.0, 3)
ylist = np.linspace(-3.0, 3.0, 4)
X, Y = np.meshgrid(xlist, ylist)
Z = np.sqrt(X**2 + Y**2)
fig = plt.figure(figsize=(7,6))
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax = fig.add_axes([left, bottom, width, height])
cp = ax.contour(X, Y, Z)
ax.clabel(cp, inline=True,
fontsize=10)
ax.set_title('Contour Plot')
ax.set_xlabel('x (cm)')
ax.set_ylabel('y (cm)')
# Z value is 1 but point is plotted beyond the 1.5 line -- why?
ax.scatter(
x=xval,
y=yval,
color="orange"
)
ax.scatter(1,1, color="red")
print(np.sqrt(1**2 + 1**2))
plt.grid()
plt.show()
You only gave matplotlib 3 points in the x-direction and 4 in the y-direction, so the interpolation that it is using to generate the contours will have a large error. Increase the number of points and you will get a more accurate result.
xlist = np.linspace(-3.0, 3.0, 100)
ylist = np.linspace(-3.0, 3.0, 100)