python绘制三维图

这篇具有很好参考价值的文章主要介绍了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')

python绘制三维图,python,matplotlib,开发语言

二、直线绘制(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()

python绘制三维图,python,matplotlib,开发语言

三、散点绘制(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()

python绘制三维图,python,matplotlib,开发语言

四、线框图(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()

python绘制三维图,python,matplotlib,开发语言

五、表面图(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()

python绘制三维图,python,matplotlib,开发语言

六、三角表面图(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()

python绘制三维图,python,matplotlib,开发语言

七、等高线(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()

python绘制三维图,python,matplotlib,开发语言

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

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

python绘制三维图,python,matplotlib,开发语言

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

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

python绘制三维图,python,matplotlib,开发语言

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

python绘制三维图,python,matplotlib,开发语言

九、子图绘制(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')

python绘制三维图,python,matplotlib,开发语言

   B-子图Subplot用法

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

python绘制三维图,python,matplotlib,开发语言

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

python绘制三维图,python,matplotlib,开发语言

 补充:

文本注释的基本用法:

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绘制三维图,python,matplotlib,开发语言文章来源地址https://www.toymoban.com/news/detail-735715.html

到了这里,关于python绘制三维图的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • python使用matplotlib库绘制数学函数

    ** ** matplotlib是python的绘画库,它可以与NumPy一起使用,提供了一种轻量级的MatLab开源高效替代方案。它可以和图形工具包PyQt等工具 一起配合使用,能够完成日常科学计算中多种数学库图可视化任务。 步骤1:使用pip安装matplotlib库 在终端输入 pip install matplotlib 命令,如下图所

    2024年02月12日
    浏览(37)
  • Python - Matplotlib 绘制 3D 圣诞树

      前言 转自: How to draw a 3D Christmas Tree with Matplotlib | by Timur Bakibayev, Ph.D. | Analytics Vidhya | Medium https://medium.com/analytics-vidhya/how-to-draw-a-3d-christmas-tree-with-matplotlib-aabb9bc27864 因为我们把圣诞树安装在暖气电池旁边,所以它很快就死了。所以我决定用 Matplotlib 绘制一棵圣诞树。你不

    2024年01月21日
    浏览(40)
  • Python中使用matplotlib绘制各类图表示例

    折线图 折线图是一种用于表示数据随时间、变量或其他连续性变化的趋势的图表。通过在横轴上放置时间或如此类似的连续变量,可以在纵轴上放置数据点的值,从而捕捉到数据随时间发生的变化。折线图可以用于比较不同变量的趋势,轻松地发现不同的变量之间的差异。

    2024年02月10日
    浏览(31)
  • 超详细的Python matplotlib 绘制柱状图

    Python 为数据展示提供了大量优秀的功能包,其中 matplotlib 模块可以方便绘制制作折线图、柱状图、散点图等高质量的数据包。 关于 matplotlib 模块,我们前期已经对matplotlib进行基本框架、以及常用方法的学习 Python matplotlib 绘制饼图_ python matplotlib绘制折线图_ python入门到进阶,

    2023年04月08日
    浏览(34)
  • python使用matplotlib实现折线图的绘制

    一、意义 数据可视化可以以简洁的方式呈现出数据,发现众多数据中隐藏的规律和意义。Matplotlib是一个数学绘图库。利用它可以制作简单的图表(散点图、折线图)。然后,将基于漫步概念生成一个更有趣的数据集–根据一系列随机决策生成的图表。本文我们主要练习折线

    2024年02月12日
    浏览(23)
  • Python中Matplotlib库的使用(三)—— Matplotlib绘制图的常用类型

    plot(x,y) plot(x, y) 函数用于绘制折线图。折线图是一种用来展示连续数据之间关系的图表类型,适用于表示数据随着一个或多个变量的变化而变化的情况。 具体来说, plot(x, y) 函数接受两个参数: x :表示X轴上的数据点的值,通常是一个数组或列表,表示自变量的取值。 y :

    2024年02月03日
    浏览(36)
  • 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 = \\\' \\\' )

    2024年02月06日
    浏览(36)
  • Python学习笔记(11-2):matplotlib绘图——图形绘制函数

    因为部分图形绘制函数共用了一套参数体系,在颜色、曲线形状等部分的使用方式也是一致的。所以,在讲解各类图形绘制之前,我们整体性地对各类通用参数进行一个整理,并在此基础上对于颜色(color)、数据点标记(marker)和曲线形式(linestyle)等几个通用参数进行相

    2024年02月06日
    浏览(42)
  • python使用matplotlib创建三维图时隐藏坐标轴、网格、背景的方法

    使用下面的代码创建一条空间直线 效果如下图所示,创建三维图形时默认会显示灰色背景、网格线以及坐标轴。 可以加入 ax.grid(None) 指令将网格设为隐藏,加入 ax.axis(\\\'off\\\') 指令将坐标轴设为隐藏 使用 可以将坐标轴的三个背景面设为白色。 加入上述指令后,代码和效果如下

    2024年02月16日
    浏览(39)
  • Python 实例|matplotlib|绘制直方图(各参数样例)

    matplotlib.pyplot.hist 的官方文档:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hist.html 这个方法使用 numpy.histogram 首先将 x 中的数据分桶并统计每个桶中的元素数量,接着使用条形图绘制这个分布。 函数参数、含义及样例如下: 参数列表及样例 x : 数据集对象(必填) (n,) arr

    2024年02月07日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包