Reputation: 171
I want to make a 3D plot for these 100 points in X,Y and Z axes. I have generated lists that I require for all 3 axes. I assumed that this should be sufficient to plot a set of points in 3D. However I do not understand the output. I appreciate any kind of help in this regard.
################################################################
# problem : f(x) = (e**(-(y**2)))*cos(3*x)+(e**(x**2))*cos(3*y)
################################################################
from mpl_toolkits.mplot3d import Axes3D
import math
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax=Axes3D(fig)
x = np.arange(-5,5,1)
y = np.arange(-5,5,1)
X = []
Y = []
Z=[]
for i in range(len(x)):
for j in range(len(y)):
z=(np.exp(-(y[j]**2))*np.cos(3*x[i]))+(np.exp(x[i]**2)*np.cos(3*y[j]))
Z.append(z)
X.append(x[i])
Y.append(y[j])
ax.plot(X,Y,Z,'o')
plt.show()
edit/update: I am not sure if my problem is with the code itself or the way i understand 3Dplots, Should I use meshgrids to get a plot that i expect?
Upvotes: 2
Views: 6203
Reputation: 46346
Which version of matplotlib do you have? The documentation states that for matplotlib versions 1.0.0 and greater you should create a 3D axes as follows:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
rather than the ax = Axes3D(fig)
used in previous versions.
Edit Following the OPs comment it seems that is the result of the code is not as expected, rather than there being some sort of error. The following code is what I presume is intended
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y = np.meshgrid(np.linspace(-5., 5., 100), np.linspace(-5., 5., 100))
def zfunc(x, y):
return np.exp(-(y**2)) * np.cos(3.*x) + np.exp(x**2) * np.cos(3.*y)
z = zfunc(x, y)
ax.plot_surface(x, y, z)
plt.show()
In the above code a two dimensional mesh is created (missing from the original post) and the function is calculated as a function of these two variables and plotted as a surface. Previously just a line of points running along x=y
was being plotting.
Upvotes: 4