引用资料:python绘制三维图 - 桂。 - 博客园

一、初始化

假设已经安装了matplotlib工具包。

利用matplotlib.figure.Figure创建一个图框:

1

2

3

4

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

二、直线绘制(Line plots)

基本用法:

1

ax.plot(x,y,z,label=' ')

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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)

= np.linspace(-22100)

= z**2 + 1

= * np.sin(theta)

= * np.cos(theta)

ax.plot(x, y, z, label='parametric curve')

ax.legend()

plt.show()

三、散点绘制(Scatter plots)

基本用法:

1

ax.scatter(xs, ys, zs, s=20, c=None, depthshade=True*args, *kwargs)

  • xs,ys,zs:输入数据;
  • s:scatter点的尺寸
  • c:颜色,如c = 'r'就是红色;
  • depthshase:透明化,True为透明,默认为True,False为不透明
  • *args等为扩展变量,如maker = 'o',则scatter结果为’o‘的形状

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

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')

= 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, 2332)

    ys = randrange(n, 0100)

    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()

四、线框图(Wireframe plots)

基本用法:

1

ax.plot_wireframe(X, Y, Z, *args, **kwargs)

  • X,Y,Z:输入数据
  • rstride:行步长
  • cstride:列步长
  • rcount:行数上限
  • ccount:列数上限

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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()

五、表面图(Surface plots)

基本用法:

1

ax.plot_surface(X, Y, Z, *args, **kwargs)

  • X,Y,Z:数据
  • rstride、cstride、rcount、ccount:同Wireframe plots定义
  • color:表面颜色
  • cmap:图层

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt

from matplotlib import cm

from matplotlib.ticker import LinearLocator, FormatStrFormatter

import numpy as np

fig = plt.figure()

ax = fig.gca(projection='3d')

# Make data.

= np.arange(-550.25)

= np.arange(-550.25)

X, Y = np.meshgrid(X, Y)

= np.sqrt(X**2 + Y**2)

= np.sin(R)

# Plot the surface.

surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,

                       linewidth=0, antialiased=False)

# Customize the z axis.

ax.set_zlim(-1.011.01)

ax.zaxis.set_major_locator(LinearLocator(10))

ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

# Add a color bar which maps values to colors.

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

六、三角表面图(Tri-Surface plots)

基本用法:

1

ax.plot_trisurf(*args, **kwargs)

  • X,Y,Z:数据
  • 其他参数类似surface-plot

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

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.1251.0, n_radii)

angles = np.linspace(02*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.

= np.append(0, (radii*np.cos(angles)).flatten())

= np.append(0, (radii*np.sin(angles)).flatten())

# Compute z to make the pringle surface.

= 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()

七、等高线(Contour plots)

基本用法:

1

ax.contour(X, Y, Z, *args, **kwargs)

code:

1

2

3

4

5

6

7

8

9

10

11

from mpl_toolkits.mplot3d import axes3d

import matplotlib.pyplot as plt

from matplotlib import cm

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

X, Y, Z = axes3d.get_test_data(0.05)

cset = ax.contour(X, Y, Z, cmap=cm.coolwarm)

ax.clabel(cset, fontsize=9, inline=1)

plt.show()

二维的等高线,同样可以配合三维表面图一起绘制:

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

from mpl_toolkits.mplot3d import axes3d

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)

ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)

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(-4040)

ax.set_ylabel('Y')

ax.set_ylim(-4040)

ax.set_zlabel('Z')

ax.set_zlim(-100100)

plt.show()

也可以是三维等高线在二维平面的投影:

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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)

ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)

cset = ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)

cset = ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)

cset = ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)

ax.set_xlabel('X')

ax.set_xlim(-4040)

ax.set_ylabel('Y')

ax.set_ylim(-4040)

ax.set_zlabel('Z')

ax.set_zlim(-100100)

plt.show()

 八、Bar plots(条形图)

基本用法:

1

ax.bar(left, height, zs=0, zdir='z'*args, **kwargs

  • x,y,zs = z,数据
  • zdir:条形图平面化的方向,具体可以对应代码理解。

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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'], [3020100]):

    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()

九、子图绘制(subplot)

  A-不同的2-D图形,分布在3-D空间,其实就是投影空间不空,对应code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

from mpl_toolkits.mplot3d import Axes3D

import numpy as np

import matplotlib.pyplot as plt

fig = plt.figure()

ax = fig.gca(projection='3d')

# Plot a sin curve using the x and y axes.

= np.linspace(01100)

= np.sin(x * 2 * np.pi) / 2 + 0.5

ax.plot(x, y, zs=0, zdir='z', label='curve in (x,y)')

# Plot scatterplot data (20 2D points per colour) on the x and z axes.

colors = ('r''g''b''k')

= np.random.sample(20*len(colors))

= np.random.sample(20*len(colors))

c_list = []

for in colors:

    c_list.append([c]*20)

# By using zdir='y', the y value of these points is fixed to the zs value 0

# and the (x,y) points are plotted on the x and z axes.

ax.scatter(x, y, zs=0, zdir='y', c=c_list, label='points in (x,z)')

# Make legend, set axes limits and labels

ax.legend()

ax.set_xlim(01)

ax.set_ylim(01)

ax.set_zlim(01)

ax.set_xlabel('X')

ax.set_ylabel('Y')

ax.set_zlabel('Z')

   B-子图Subplot用法

与MATLAB不同的是,如果一个四子图效果,如:

MATLAB:

1

2

3

subplot(2,2,1)

subplot(2,2,2)

subplot(2,2,[3,4])

Python:

1

2

3

subplot(2,2,1)

subplot(2,2,2)

subplot(2,1,2)

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data

from matplotlib import cm

import numpy as np

# set up a figure twice as wide as it is tall

fig = plt.figure(figsize=plt.figaspect(0.5))

#===============

#  First subplot

#===============

# set up the axes for the first plot

ax = fig.add_subplot(221, projection='3d')

# plot a 3D surface like in the example mplot3d/surface3d_demo

= np.arange(-550.25)

= np.arange(-550.25)

X, Y = np.meshgrid(X, Y)

= np.sqrt(X**2 + Y**2)

= np.sin(R)

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,

                       linewidth=0, antialiased=False)

ax.set_zlim(-1.011.01)

fig.colorbar(surf, shrink=0.5, aspect=10)

#===============

# Second subplot

#===============

# set up the axes for the second plot

ax = fig.add_subplot(2,1,2, projection='3d')

# plot a 3D wireframe like in the example mplot3d/wire3d_demo

X, Y, Z = get_test_data(0.05)

ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

plt.show()

 补充:

文本注释的基本用法:

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

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', (110), (111))

xs = (144941)

ys = (2581012)

zs = (1038918)

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(900"red", color='red')

# Demo 3: text2D

# Placement 0, 0 would be the bottom left, 1, 1 would be the top right.

ax.text2D(0.050.95"2D Text", transform=ax.transAxes)

# Tweaking display region and labels

ax.set_xlim(010)

ax.set_ylim(010)

ax.set_zlim(010)

ax.set_xlabel('X axis')

ax.set_ylabel('Y axis')

ax.set_zlabel('Z axis')

plt.show()

参考:Python画几何二维图 - Roboleofly - 博客园

在python用matplotlib库进行三维绘制相关推荐

  1. python的matplotlib库绘制条形图、散点图、饼图、折线图

    python的matplotlib库绘制条形图.散点图.饼图.折线图 当我们学会了爬虫,抓取到了一些数据,接下来就是做数据分析了.本文章介绍绘制图形的基本代码. 打开cmd用pip 安装,若输入pip ...

  2. Python学习-Matplotlib库绘制简单点阵图、线型图操作

    Python学习-Matplotlib库绘制简单散点图图和线型图.标签设置以及刻度线设置操作 目录 1.Matplotlib绘图细节的简单理解 2.绘制点图.线型图 3.给图表设置复杂标注 4.移动刻 ...

  3. python 颜色_如何使用python中matplotlib库分析图像颜色

    用代码分析图像可能很困难.你如何使代码"理解"图像的上下文? 通常,使用AI分析图像的第一步 是找到主要颜色.在如何使用python中matplotlib库分析图像颜色中,我们将使 ...

  4. 使用Python的Cufflinks库创建三维散点图

    使用Python的Cufflinks库创建三维散点图 在数据可视化中,三维散点图是一种常用的图形展示方式.如果您正在寻找一种方便易用的数据可视化工具来创建三维散点图,那么Cufflinks就是一个不错 ...

  5. python如何安装matplotlib_详解python安装matplotlib库三种失败情况

    (可能只有最后一句命令有用,可能全篇都没用) (小白方法,可能只适用于本人情况) 安装matplotlib时,出现的三种失败情况 1.read timed out 一开始我在pycharm终端使用pi ...

  6. Python的matplotlib库画图不能显示中文问题解决

    Python的matplotlib库画图不能显示中文问题解决 参考文章: (1)Python的matplotlib库画图不能显示中文问题解决 (2)https://www.cnblogs.com/CQ ...

  7. Ubuntu16.04 下python的matplotlib库加入中文字体(微软雅黑)

    Ubuntu16.04 下python的matplotlib库加入中文字体 一.首先安装微软雅黑字体 1.下载或者拷贝微软雅黑字体 2.将待安装的字体复制到Ubuntu下面的字体位置`/usr/sha ...

  8. Python 之matplotlib库的安装及Read timed out Error的解决方案

    Python 之matplotlib库的安装 打开cmd窗口.点击开始栏,搜索cmd并打开. 找到安装的Python路径.可以通过右键点击Python快捷键,查找文件路径.(博主电脑并未分盘,故安装到 ...

  9. python的matplotlib库怎么安装,用pip给python安装matplotlib库的详细教程

    Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形. 1.首先在python里安装pip,打开安装python的文件夹,找到pyt ...

最新文章

  1. 关于Transformer,那些的你不知道的事
  2. 简单的活又谈何容易呢
  3. FPGA中时钟相关概念
  4. Linux下gcc中各种文件后缀说明
  5. UnisGuard防篡改产品了解
  6. Linux学习之CentOS(五)--让我有些郁闷的mount命令
  7. 区块链跟银行有什么关系?
  8. 洛谷P1134阶乘问题(数论,末尾0的个数变形,思维转换)
  9. 2017-06-30
  10. 使用sp_addlinkedserver、sp_dropserver 、sp_addlinkedsrvlogin和sp_droplinkedsrvlogin 远程查询数据...
  11. 表单从gb2312的页面提交到utf-8页面,或者表单从utf-8的页面提交到gb2312页面的解决办法...
  12. 07. 千万不要重载、||和, 操作符
  13. JUL(java.util.logging)java原生官方日志 使用与配置--解决jul不输出显示日志问题
  14. bilibili直播 斗鱼直播等直播工具黑屏怎么办?
  15. 名帖121 文徵明 小楷《琴赋》
  16. 新颖的自我介绍_简单新颖的自我介绍范文
  17. ES6 trim()方法
  18. RPA - Robotic process automation (机器人流程自动化)
  19. 重温与解析《最后生还者》的互动叙事精髓(上)
  20. 发散性测试用例设计题

热门文章

  1. csv导出文件名乱码解决
  2. 重学JS(一):什么是枚举?
  3. MySQL数据库下载与安装详细教程
  4. html选择按键点击后锁死输入框_js Dom为页面中的元素绑定键盘或鼠标事件
  5. TTL expired in transit
  6. 山寨 悟空遥控器的 方向键
  7. 函数的定义以及关键字参数
  8. 微信扫描二维码网页跳转显示信息
  9. QT 自定义带图片背景半透明阴影窗口
  10. 操作系统原理——第2章 操作系统概述