Python绘制3D图形


Posted in Python onMay 03, 2018

3D图形在数据分析、数据建模、图形和图像处理等领域中都有着广泛的应用,下面将给大家介绍一下如何使用python进行3D图形的绘制,包括3D散点、3D表面、3D轮廓、3D直线(曲线)以及3D文字等的绘制。

准备工作:

python中绘制3D图形,依旧使用常用的绘图模块matplotlib,但需要安装mpl_toolkits工具包,安装方法如下:windows命令行进入到python安装目录下的Scripts文件夹下,执行: pip install --upgrade matplotlib即可;linux环境下直接执行该命令。

安装好这个模块后,即可调用mpl_tookits下的mplot3d类进行3D图形的绘制。

下面以实例进行说明。

1、3D表面形状的绘制

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
import numpy as np 
 
fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
 
# Make data 
u = np.linspace(0, 2 * np.pi, 100) 
v = np.linspace(0, np.pi, 100) 
x = 10 * np.outer(np.cos(u), np.sin(v)) 
y = 10 * np.outer(np.sin(u), np.sin(v)) 
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) 
 
# Plot the surface 
ax.plot_surface(x, y, z, color='b') 
 
plt.show()

球表面,结果如下:

Python绘制3D图形

2、3D直线(曲线)的绘制

import matplotlib as mpl 
from mpl_toolkits.mplot3d import Axes3D 
import numpy as np 
import matplotlib.pyplot as plt 
 
mpl.rcParams['legend.fontsize'] = 10 
 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) 
z = np.linspace(-2, 2, 100) 
r = z**2 + 1 
x = r * np.sin(theta) 
y = r * np.cos(theta) 
ax.plot(x, y, z, label='parametric curve') 
ax.legend() 
 
plt.show()

这段代码用于绘制一个螺旋状3D曲线,结果如下:

Python绘制3D图形

3、绘制3D轮廓

from mpl_toolkits.mplot3d import axes3d 
import matplotlib.pyplot as plt 
from matplotlib import cm 
 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
X, Y, Z = axes3d.get_test_data(0.05) 
cset = ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm) 
cset = ax.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm) 
cset = ax.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm) 
 
ax.set_xlabel('X') 
ax.set_xlim(-40, 40) 
ax.set_ylabel('Y') 
ax.set_ylim(-40, 40) 
ax.set_zlabel('Z') 
ax.set_zlim(-100, 100) 
 
plt.show()

绘制结果如下:

Python绘制3D图形

4、绘制3D直方图

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
import numpy as np 
 
fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
x, y = np.random.rand(2, 100) * 4 
hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]]) 
 
# Construct arrays for the anchor positions of the 16 bars. 
# Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos, 
# ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid 
# with indexing='ij'. 
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25) 
xpos = xpos.flatten('F') 
ypos = ypos.flatten('F') 
zpos = np.zeros_like(xpos) 
 
# Construct arrays with the dimensions for the 16 bars. 
dx = 0.5 * np.ones_like(zpos) 
dy = dx.copy() 
dz = hist.flatten() 
 
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average') 
 
plt.show()

绘制结果如下:

Python绘制3D图形

5、绘制3D网状线

from mpl_toolkits.mplot3d import axes3d 
import matplotlib.pyplot as plt 
 
 
fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
 
# Grab some test data. 
X, Y, Z = axes3d.get_test_data(0.05) 
 
# Plot a basic wireframe. 
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) 
 
plt.show()

绘制结果如下:

Python绘制3D图形

6、绘制3D三角面片图

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
import numpy as np 
 
 
n_radii = 8 
n_angles = 36 
 
# Make radii and angles spaces (radius r=0 omitted to eliminate duplication). 
radii = np.linspace(0.125, 1.0, n_radii) 
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False) 
 
# Repeat all angles for each radius. 
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) 
 
# Convert polar (radii, angles) coords to cartesian (x, y) coords. 
# (0, 0) is manually added at this stage, so there will be no duplicate 
# points in the (x, y) plane. 
x = np.append(0, (radii*np.cos(angles)).flatten()) 
y = np.append(0, (radii*np.sin(angles)).flatten()) 
 
# Compute z to make the pringle surface. 
z = np.sin(-x*y) 
 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
 
ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True) 
 
plt.show(

绘制结果如下:

Python绘制3D图形

7、绘制3D散点图

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
import numpy as np 
 
 
def randrange(n, vmin, vmax): 
 ''''' 
 Helper function to make an array of random numbers having shape (n, ) 
 with each number distributed Uniform(vmin, vmax). 
 ''' 
 return (vmax - vmin)*np.random.rand(n) + vmin 
 
fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
 
n = 100 
 
# For each set of style and range settings, plot n random points in the box 
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh]. 
for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]: 
 xs = randrange(n, 23, 32) 
 ys = randrange(n, 0, 100) 
 zs = randrange(n, zlow, zhigh) 
 ax.scatter(xs, ys, zs, c=c, marker=m) 
 
ax.set_xlabel('X Label') 
ax.set_ylabel('Y Label') 
ax.set_zlabel('Z Label') 
 
plt.show()

绘制结果如下:

Python绘制3D图形

8、绘制3D文字

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
 
 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
 
# Demo 1: zdir 
zdirs = (None, 'x', 'y', 'z', (1, 1, 0), (1, 1, 1)) 
xs = (1, 4, 4, 9, 4, 1) 
ys = (2, 5, 8, 10, 1, 2) 
zs = (10, 3, 8, 9, 1, 8) 
 
for zdir, x, y, z in zip(zdirs, xs, ys, zs): 
 label = '(%d, %d, %d), dir=%s' % (x, y, z, zdir) 
 ax.text(x, y, z, label, zdir) 
 
# Demo 2: color 
ax.text(9, 0, 0, "red", color='red') 
 
# Demo 3: text2D 
# Placement 0, 0 would be the bottom left, 1, 1 would be the top right. 
ax.text2D(0.05, 0.95, "2D Text", transform=ax.transAxes) 
 
# Tweaking display region and labels 
ax.set_xlim(0, 10) 
ax.set_ylim(0, 10) 
ax.set_zlim(0, 10) 
ax.set_xlabel('X axis') 
ax.set_ylabel('Y axis') 
ax.set_zlabel('Z axis') 
 
plt.show(

绘制结果如下:

Python绘制3D图形

9、3D条状图

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
import numpy as np 
 
fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]): 
 xs = np.arange(20) 
 ys = np.random.rand(20) 
 
 # You can provide either a single color or an array. To demonstrate this, 
 # the first bar of each set will be colored cyan. 
 cs = [c] * len(xs) 
 cs[0] = 'c' 
 ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8) 
 
ax.set_xlabel('X') 
ax.set_ylabel('Y') 
ax.set_zlabel('Z') 
 
plt.show()

绘制结果如下:

Python绘制3D图形

以上所述是小编给大家介绍的python绘制3D图形,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持

Python 相关文章推荐
Python中的with语句与上下文管理器学习总结
Jun 28 Python
Python数据可视化正态分布简单分析及实现代码
Dec 04 Python
解决Python requests库编码 socks5代理的问题
May 07 Python
Django实现发送邮件功能
Jul 18 Python
python中@property和property函数常见使用方法示例
Oct 21 Python
Pyorch之numpy与torch之间相互转换方式
Dec 31 Python
python matplotlib模块基本图形绘制方法小结【直线,曲线,直方图,饼图等】
Apr 26 Python
详解python如何引用包package
Jun 07 Python
python中的对数log函数表示及用法
Dec 09 Python
Django程序的优化技巧
Apr 29 Python
Python机器学习之基础概述
May 19 Python
python字符串的多行输出的实例详解
Jun 08 Python
Python学习_几种存取xls/xlsx文件的方法总结
May 03 #Python
Python使用win32 COM实现Excel的写入与保存功能示例
May 03 #Python
python调用xlsxwriter创建xlsx的方法
May 03 #Python
Python基于opencv的图像压缩算法实例分析
May 03 #Python
python实现数据导出到excel的示例--普通格式
May 03 #Python
python操作xlsx文件的包openpyxl实例
May 03 #Python
对Python字符串中的换行符和制表符介绍
May 03 #Python
You might like
显示youtube视频缩略图和Vimeo视频缩略图代码分享
2014/02/13 PHP
php常用数学函数汇总
2014/11/21 PHP
Thinkphp实现短信验证注册功能
2016/10/18 PHP
php实现文件上传基本验证
2020/03/04 PHP
jQuery基于当前元素进行下一步的遍历
2014/05/20 Javascript
JavaScript弹出窗口方法汇总
2014/08/12 Javascript
基于JavaScript实现鼠标箭头移动图片跟着移动
2016/08/30 Javascript
jQuery为某个div加入行样式
2017/06/09 jQuery
通过学习bootstrop导航条学会修改bootstrop颜色基调
2017/06/11 Javascript
vue时间格式化实例代码
2017/06/13 Javascript
解决vue处理axios post请求传参的问题
2018/03/05 Javascript
使用JavaScript保存文本文件到本地的两种方法
2019/01/22 Javascript
this.$toast() 了解一下?
2019/04/18 Javascript
vue.js实现h5机器人聊天(测试版)
2020/07/16 Javascript
ant-design-vue中tree增删改的操作方法
2020/11/03 Javascript
详解为什么Vue中的v-if和v-for不建议一起用
2021/01/13 Vue.js
python使用新浪微博api上传图片到微博示例
2014/01/10 Python
简单了解Python matplotlib线的属性
2019/06/29 Python
详解如何减少python内存的消耗
2019/08/09 Python
Python django框架输入汉字,数字,字符生成二维码实现详解
2019/09/24 Python
python实现可下载音乐的音乐播放器
2020/02/25 Python
2020新版本pycharm+anaconda+opencv+pyqt环境配置学习笔记,亲测可用
2020/03/24 Python
如何让python的运行速度得到提升
2020/07/08 Python
Python fileinput模块如何逐行读取多个文件
2020/10/05 Python
沙特阿拉伯网上购物:Sayidaty Mall
2018/05/06 全球购物
经典促销广告词大全
2014/03/19 职场文书
《风筝》教学反思
2014/04/10 职场文书
水利水电专业自荐信
2014/07/08 职场文书
教师批评与自我批评剖析材料
2014/10/16 职场文书
2014年体育教师工作总结
2014/12/03 职场文书
2014年教育培训工作总结
2014/12/08 职场文书
大学开学典礼新闻稿
2015/07/17 职场文书
2016幼儿教师自荐信范文
2016/01/28 职场文书
2016优秀教师先进个人事迹材料
2016/02/25 职场文书
Spring Boot 启动、停止、重启、状态脚本
2021/06/26 Java/Android
Python Django获取URL中的数据详解
2021/11/01 Python