0

I noticed something unusual with a code I wrote that I didn't understand. The problem was to plot a contour plot in python. Here is the code I wrote(Which is mistakenly wrong since I have to pass the plt.contour() instead of plt.plot()):

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def f(x,y):
    return (x**2+y**2)/np.sqrt(x**2+y**2)
    
x=np.linspace(0,1,11)
y=np.linspace(0,1,11)



X,Y=np.meshgrid(x,y)
z=f(X,Y)
print(np.shape(z))


plt.plot(x,y,z)
plt.show()

Now, I though that this programme would throw an error since x and y are 1-D array and z is 11×11 array. However,to my surprise it didn't. Instead it plotted the curves as shown below: enter image description here

I checked the official documentation and according to it,this call is perfectly allowed. However, the trouble part is I don't know what the code actually did. Why are the curves actually plotted like the one in figure given below? There is no mention in official documentation that how such call to the function works. Can someone explain what this code actually did? I have hard time understanding this.

1 Answer 1

1

Is this what you are trying to plot?

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def f(x,y):
    return (x**2+y**2)/np.sqrt(x**2+y**2)
    
x=np.linspace(0,1,11)
y=np.linspace(0,1,11)

X,Y=np.meshgrid(x,y)
z=f(X,Y)
 
fig = plt.figure()              #<----
ax = plt.axes(projection='3d')  #<----
ax.contour3D(X, Y, z)           #<----
plt.show()

enter image description here


Regarding the lack of an error/warning:

Why are the curves actually plotted like the one in figure given below?

Check this out for details What does the third parameter of plt.plot() in matplotlib do?

Sign up to request clarification or add additional context in comments.

2 Comments

Well, this was what I intended to plot. However, as I said I mistakenly passed plt.plot() instead of plt.contour() and I got the output as I showed in question. My question actually was what the code actually did that I got such strange output (They are definately not circles!)? To the plt.plot() I passed 3 arrays: Two 1-D array and one (11×11) array and it gave me output as I put in the question .
Ah ok, does this answer your question? (updated my answer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.