“上一节我们学习了如何绘制3D散点图,这一节我们主要学习如何绘制3D曲面图,以及绘制多组曲面图。”
3D曲面图
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建数据
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
# 创建画布和坐标轴
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 绘制3D曲面图
ax.plot_surface(X, Y, Z, cmap='viridis')
# 设置坐标轴标签
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# 设置标题
ax.set_title('3D Surface Plot')
# 显示图形
plt.show()
自定义3D曲面图
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
prices = np.array([10, 20, 30, 40, 50, 60, 70, 80])
sales = np.array([100, 150, 200, 250, 300, 350, 400, 450])
price, sale = np.meshgrid(prices, sales)
performance = np.array([
[ ],
[ ],
[ ],
[ ],
[ ],
[ ],
[ ],
[ ]
])
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(price, sale, performance, cmap='coolwarm')
ax.set_xlabel('Price')
ax.set_ylabel('Sales')
ax.set_zlabel('Performance')
ax.set_title('Sales Performance with Price and Sales')
plt.show()
绘制多个3D曲面图
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建数据
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z1 = np.sin(np.sqrt(X**2 + Y**2))
Z2 = np.cos(X) * np.sin(Y)
Z3 = np.exp(-(X**2 + Y**2)/10) * np.cos(np.sqrt(X**2 + Y**2))
# 创建画布和子图
fig = plt.figure()
# 子图1
ax1 = fig.add_subplot(131, projection='3d')
ax1.plot_surface(X, Y, Z1, cmap='viridis')
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
ax1.set_zlabel('Z1')
# 子图2
ax2 = fig.add_subplot(132, projection='3d')
ax2.plot_surface(X, Y, Z2, cmap='plasma')
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
ax2.set_zlabel('Z2')
# 子图3
ax3 = fig.add_subplot(133, projection='3d')
ax3.plot_surface(X, Y, Z3, cmap='magma')
ax3.set_xlabel('X')
ax3.set_ylabel('Y')
ax3.set_zlabel('Z3')
# 设置整体标题
fig.suptitle('Multiple 3D Surface Plots')
# 调整子图布局
fig.tight_layout()
# 显示图形
plt.show()
总结 由于微信订阅号的推送规则越来越迷,为防止错过精彩连载内容,请将我们的公众号设为星标,方法如下:
参考资料
https://matplotlib.org/stable/plot_types/3D/surface3d_simple.html
[2] Python绘图——3D散点图
作者:三五七
微信扫一扫
关注该公众号