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的基础画法。

相关推荐
阿耶同学2 分钟前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田16 小时前
Pydantic校验配置文件
python
hboot17 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉
韩师傅2 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉