Python利用matplotlib模块数据可视化绘制3D图

 更新时间:2022年02月10日 11:21:59   作者:嫑叫我  
matplotlib是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地行制图,下面这篇文章主要给大家介绍了关于Python利用matplotlib模块数据可视化实现3D图的相关资料,需要的朋友可以参考下

前言

matplotlib实际上是一套面向对象的绘图库,它所绘制的图表中的每个绘图元素,例如线条Line2D、文字Text、刻度等在内存中都有一个对象与之对应。

为了方便快速绘图matplotlib通过pyplot模块提供了一套和MATLAB类似的绘图API,将众多绘图对象所构成的复杂结构隐藏在这套API内部。我们只需要调用pyplot模块所提供的函数就可以实现快速绘图以及设置图表的各种细节。pyplot模块虽然用法简单,但不适合在较大的应用程序中使用。

为了将面向对象的绘图库包装成只使用函数的调用接口,pyplot模块的内部保存了当前图表以及当前子图等信息。当前的图表和子图可以使用plt.gcf()和plt.gca()获得,分别表示"Get Current Figure"和"Get Current Axes"。在pyplot模块中,许多函数都是对当前的Figure或Axes对象进行处理,比如说:

plt.plot()实际上会通过plt.gca()获得当前的Axes对象ax,然后再调用ax.plot()方法实现真正的绘图。

可以在Ipython中输入类似"plt.plot??"的命令查看pyplot模块的函数是如何对各种绘图对象进行包装的。

1 matplotlib绘制3D图形

matplotlib可以绘制3D图形,有的版本中不具备该模块,可以进入python环境,输入from mpl_toolkits.mplot3d import Axes3D进行测试,如果导入成功则可以,否则需要安装matplotlib其他版本,这里我用的是2.0.2版本。

2 绘制3D画面图

2.1 源码

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
# 创建3d图形的两种方式
# ax = Axes3D(fig)
ax = fig.add_subplot(111, projection='3d')
# X, Y value
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)    # x-y 平面的网格
R = np.sqrt(X ** 2 + Y ** 2)
# height value
Z = np.sin(R)
# rstride:行之间的跨度  cstride:列之间的跨度
# rcount:设置间隔个数,默认50个,ccount:列的间隔个数  不能与上面两个参数同时出现
#vmax和vmin  颜色的最大值和最小值
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
# zdir : 'z' | 'x' | 'y' 表示把等高线图投射到哪个面
# offset : 表示等高线图投射到指定页面的某个刻度
ax.contourf(X,Y,Z,zdir='z',offset=-2)
# 设置图像z轴的显示范围,x、y轴设置方式相同
ax.set_zlim(-2,2)
plt.show()

2.2 效果图

3 绘制散点图

3.1 源码

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
 
x = np.arange(0, 200)
y = np.arange(0, 100)
x, y = np.meshgrid(x, y)
z = np.random.randint(0, 200, size=(100, 200))
y3 = np.arctan2(x,y)
ax.scatter(x, y, z, c=y3, marker='.', s=50, label='')
plt.show()

3.2 效果图

4 绘制多边形

4.1 源码

from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection,Line3DCollection
fig = plt.figure()
ax = fig.gca(projection='3d')
 
# 正文体顶点和面
verts = [(0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1), (1, 0, 1)]
faces = [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [0, 3, 7, 4]]
# 四面体顶点和面
# verts = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (1, 0, 1)]
# faces = [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]
# 获得每个面的顶点
poly3d = [[verts[vert_id] for vert_id in face] for face in faces]
# print(poly3d)
 
# 绘制顶点
x, y, z = zip(*verts)
ax.scatter(x, y, z)
# 绘制多边形面
ax.add_collection3d(Poly3DCollection(poly3d, facecolors='w', linewidths=1, alpha=0.3))
# 绘制对变形的边
ax.add_collection3d(Line3DCollection(poly3d, colors='k', linewidths=0.5, linestyles=':'))
 
 # 设置图形坐标范围
ax.set_xlabel('X')
ax.set_xlim3d(-0.5, 1.5)
ax.set_ylabel('Y')
ax.set_ylim3d(-0.5, 1.5)
ax.set_zlabel('Z')
ax.set_zlim3d(-0.5, 1.5)
plt.show()

4.2 效果图

5 三个方向有等高线的3D图

5.1 源码

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.5,color='b')
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()

5.2 效果图

6 三维柱状图

6.1 源码

import random
import matplotlib as mpl
import matplotlib.dates as mdates
from mpl_toolkits.mplot3d import Axes3D
mpl.rcParams['font.size'] = 10
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for z in [2011, 2012, 2013, 2014]:
    xs = range(1,13)
    ys = 1000 * np.random.rand(12)
    color = plt.cm.Set2(random.choice(range(plt.cm.Set2.N)))
    ax.bar(xs, ys, zs=z, zdir='y', color=color, alpha=0.8)
 
ax.xaxis.set_major_locator(mpl.ticker.FixedLocator(xs))
ax.yaxis.set_major_locator(mpl.ticker.FixedLocator(ys))
ax.set_xlabel('Month')
ax.set_ylabel('Year')
ax.set_zlabel('Sales Net [usd]')
plt.show()

6.2 效果图

7 补充图

7.1 源码

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
 
n_angles = 36
n_radii = 8
# An array of radii
# Does not include radius r=0, this is to eliminate duplicate points
radii = np.linspace(0.125, 1.0, n_radii)
# An array of angles
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 added here. There are 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())
# Pringle surface
z = np.sin(-x * y)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.2)
plt.show()

7.2 效果图

说明:内容太多,这里都是做了源码和效果图展示,记得在使用中导入import matplotlib.pyplot as plt,否则会报错;对于import numpy as np模块根据实际情况导入,如果没有使用该模块构造数据的,可以不导入。

总结

到此这篇关于Python利用matplotlib模块数据可视化绘制3D图的文章就介绍到这了,更多相关matplotlib模块数据可视化3D图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Pygame浅析动画精灵和碰撞检测实现方法

    Pygame浅析动画精灵和碰撞检测实现方法

    这篇文章主要介绍了利用pygame完成动画精灵和碰撞检测,代码详细,内容丰富,对于想要学习pygame的朋友来讲是一个不错的练习,需要的朋友可以参考下
    2023-01-01
  • python 计算两个列表的相关系数的实现

    python 计算两个列表的相关系数的实现

    这篇文章主要介绍了python 计算两个列表的相关系数的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08
  • 如何在python中实现随机选择

    如何在python中实现随机选择

    这篇文章主要介绍了如何在python中实现随机选择,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • python 如何调用 dubbo 接口

    python 如何调用 dubbo 接口

    这篇文章主要介绍了python 如何调用 dubbo 接口,帮助大家更好的理解和学习python,感兴趣的朋友可以了解下
    2020-09-09
  • Pytorch各种维度变换函数总结

    Pytorch各种维度变换函数总结

    本文对于PyTorch中的各种维度变换的函数进行总结,包括reshape()、view()、resize_()、transpose()、permute()、squeeze()、unsqeeze()、expand()、repeat()函数的介绍和对比,感兴趣的可以了解一下
    2024-02-02
  • 基于python实现新春烟花盛宴效果

    基于python实现新春烟花盛宴效果

    这篇文章给大家用Python绽放了一场新春烟花盛宴,这里提前祝大家新春快乐呀,文中通过代码示例给大家介绍的非常详细,感兴趣的小伙伴可以自己动手尝试一下
    2024-02-02
  • Python CategoricalDtype自定义排序实现原理解析

    Python CategoricalDtype自定义排序实现原理解析

    这篇文章主要介绍了Python CategoricalDtype自定义排序实现原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • Python切片知识解析

    Python切片知识解析

    这篇文章主要介绍了Python切片知识解析的相关资料,需要的朋友可以参考下
    2016-03-03
  • 利用Tensorflow构建和训练自己的CNN来做简单的验证码识别方式

    利用Tensorflow构建和训练自己的CNN来做简单的验证码识别方式

    今天小编就为大家分享一篇利用Tensorflow构建和训练自己的CNN来做简单的验证码识别方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • python实现停车管理系统

    python实现停车管理系统

    这篇文章主要为大家详细介绍了python实现停车管理系统,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-11-11

最新评论