“上一节我们学习了如何绘制3D散点图,这一节我们主要学习如何绘制3D曲面图,以及绘制多组曲面图。” 统计分析与数据挖掘推荐搜索
3D曲面图
import numpy as npimport matplotlib.pyplot as pltfrom 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 npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dprices = 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 npimport matplotlib.pyplot as pltfrom 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()# 子图1ax1 = 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')# 子图2ax2 = 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')# 子图3ax3 = 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散点图
作者:三五七
微信扫一扫
关注该公众号