python画图|3D surface基础教程

画三维图在当前的需求越来越强烈,因此掌握3D图的画法至关重要。

让我们先来学习3D surface基础教程。

【1】官网教程

首先是来到官网,找到教程,详见下述链接:

3D surface (colormap) --- Matplotlib 3.9.2 documentation

教程页面给出了漂亮的3D surface图形,具体代码解释如下。

【2】代码解读

首先是引入numpyh和matplotlib:

复制代码
import matplotlib.pyplot as plt #引入matplotlib模块画图
import numpy as np #引入numpy模块做数学计算

from matplotlib import cm #cm即是colormap,引入该模块支持渐变颜色绘制
from matplotlib.ticker import LinearLocator #引入线性化画图模块

然后定义了变量:

复制代码
fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) #定义画图

# Make data.
X = np.arange(-5, 5, 0.25) #定义X范围
Y = np.arange(-5, 5, 0.25) #定义Y范围
X, Y = np.meshgrid(X, Y) #输出组合组矩阵
R = np.sqrt(X**2 + Y**2) #定义R变量
Z = np.sin(R) #定义Z变量

之后定义了要画surface图:

复制代码
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False) #定义画surface图

剩下的部分先定义了坐标轴:

复制代码
ax.set_zlim(-1.01, 1.01) #限定Z轴
ax.zaxis.set_major_locator(LinearLocator(10)) #限定线性化位置
# A StrMethodFormatter is used automatically
ax.zaxis.set_major_formatter('{x:.02f}') #设置坐标格式

最后定义了图形颜色和要求输出图形:

复制代码
fig.colorbar(surf, shrink=0.5, aspect=5) #定义图形渐变

plt.show()

++图1++

【2】代码修改

尝试修改LinearLocator(30)为30,改后:

复制代码
ax.zaxis.set_major_locator(LinearLocator(30)) #限定线性化位置
复制代码
输出结果为:

++图2++

图形层数变得密集。

【3】总结

学习了3Dsurface的基础画法。

相关推荐
默_笙1 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003961 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫1 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技1 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时2 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车2 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊2 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1232 天前
2026年第38周GitHub趋势周报
python·科技·github