from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
def draw3Dcontour(func, s= "x^2 + y^3"):
x = np.arange(-2*np.pi, 2*np.pi, 0.5)
y = np.arange(-2*np.pi, 2*np.pi, 0.5)
X, Y = np.meshgrid(x,y)
Z = func(X,Y)#X ** 2 + Y ** 3
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X,Y,Z, rstride=8, cstride=8, alpha = 0.3)
cset = ax.contour(X,Y,Z, zdir='z', offset= np.min(np.array(Z)), cmap = cm.coolwarm)
cset = ax.contour(X,Y,Z, zdir = 'x', offset = -6, cmap = cm.coolwarm)
cset = ax.contour(X,Y,Z, zdir = 'y', offset = 6, cmap = cm.coolwarm)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title(s)
# plt.show()
draw3Dcontour(lambda X,Y : X**2 + Y**2, "x^2+y^2")
## 1 : "x^2 + y^3"
draw3Dcontour(lambda X,Y : X**2 + Y**3, "x^2+y^3")
draw3Dcontour(lambda X,Y : np.sin(X) + np.cos(Y), "sinx+cosy") # sin(x), cos(y)
draw3Dcontour(lambda X,Y : np.abs(X) @ np.sin(X) + np.cos(Y), "sinx+cosy") # sin(x), cos(y)
plt.show()
原版样例
'''
======================================
Projecting filled contour onto a graph
======================================
Demonstrates displaying a 3D surface while also projecting filled contour
'profiles' onto the 'walls' of the graph.
See contour3d_demo2 for the unfilled version.
'''
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
# Plot the 3D surface
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
# Plot projections of the contours for each dimension. By choosing offsets
# that match the appropriate axes limits, the projected contours will sit on
# the 'walls' of the graph
cset = ax.contourf(X, Y, Z, zdir='z', cmap=cm.coolwarm) # offset=-100,
cset = ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)
ax.set_xlim(-40, 40)
ax.set_ylim(-40, 40)
ax.set_zlim(-100, 100)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
样例是一个峰-谷图,有点高端的,我改了一些,方便常见的图形暂时;具体图形因为程序问题,不上传了,感兴趣读者自己run一下。