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

相关推荐
东莞市云毅网络有限公司几秒前
SQLite FTS5 做中文问答检索:分词、排序与召回测试
python·sqlite·自动化运维·geo·数据监测
codeejun8 分钟前
每日一Go·MySQL-22、幻读、不可重复读、脏读实战演示
开发语言·mysql·golang
云草桑20 分钟前
C#入坑JAVA 潜规则 API Get 多参数 Spring Boot与Spring Cloud 区别 入门系列4
java·开发语言
码途行者9 小时前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
头发还在的女程序员9 小时前
Java充电桩平台源码解析:枪口状态、上报时间与页面刷新怎样协同
java·开发语言·充电桩系统·充电桩管理·充电系统·充电小程序
timeDifference₇10 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu11 小时前
python:DecisionTree
开发语言·后端·python·算法
怒放的生命199112 小时前
代码知识库 RAG 问答系统 —— 从 0 到 1 实现教程
python·状态模式·fastapi·全栈开发·ai agent应用开发
geovindu13 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
fengkai454513 小时前
Python运维
运维·python·监控·psutil·ipy