当前位置:   article > 正文

python3d画图mpl_toolkits.mplot3d_from mpl_toolkits.mplot3d import axes3d

from mpl_toolkits.mplot3d import axes3d

Line plot

  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. import matplotlib as mpl
  4. import matplotlib.pyplot as plt
  5. from mpl_toolkits.mplot3d import Axes3D
  6. mpl.rcParams['legend.fontsize'] = 20 # mpl模块载入的时候加载配置信息存储在rcParams变量中,rc_params_from_file()函数从文件加载配置信息
  7. font = {
  8. 'color': 'b',
  9. 'style': 'oblique',
  10. 'size': 20,
  11. 'weight': 'bold'
  12. }
  13. fig = plt.figure(figsize=(16, 12)) #参数为图片大小
  14. ax = fig.gca(projection='3d') # get current axes,且坐标轴是3d的
  15. # 准备数据
  16. theta = np.linspace(-8 * np.pi, 8 * np.pi, 100) # 生成等差数列,[-8π,8π],个数为100
  17. z = np.linspace(-2, 2, 100) # [-2,2]容量为100的等差数列,这里的数量必须与theta保持一致,因为下面要做对应元素的运算
  18. r = z ** 2 + 1
  19. x = r * np.sin(theta) # [-5,5]
  20. y = r * np.cos(theta) # [-5,5]
  21. ax.set_xlabel("X", fontdict=font)
  22. ax.set_ylabel("Y", fontdict=font)
  23. ax.set_zlabel("Z", fontdict=font)
  24. ax.set_title("Line Plot", alpha=0.5, fontdict=font) #alpha参数指透明度transparent
  25. ax.plot(x, y, z, label='parametric curve')
  26. ax.legend(loc='upper right') #legend的位置可选:upper right/left/center,lower right/left/center,right,left,center,best等等
  27. plt.show()
  • 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

Scatter plot

  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. import matplotlib as mpl
  4. import matplotlib.pyplot as plt
  5. from mpl_toolkits.mplot3d import Axes3D
  6. label_font = {
  7. 'color': 'c',
  8. 'size': 15,
  9. 'weight': 'bold'
  10. }
  11. def randrange(n, vmin, vmax):
  12. r = np.random.rand(n) # 随机生成n个介于0~1之间的数
  13. return (vmax - vmin) * r + vmin # 得到n个[vmin,vmax]之间的随机数
  14. fig = plt.figure(figsize=(16, 12))
  15. ax = fig.add_subplot(111, projection="3d") # 添加子坐标轴,111表示1行1列的第一个子图
  16. n = 200
  17. for zlow, zhigh, c, m, l in [(4, 15, 'r', 'o', 'positive'),
  18. (13, 40, 'g', '*', 'negative')]: # 用两个tuple,是为了将形状和颜色区别开来
  19. x = randrange(n, 15, 40)
  20. y = randrange(n, -5, 25)
  21. z = randrange(n, zlow, zhigh)
  22. ax.scatter(x, y, z, c=c, marker=m, label=l, s=z * 10) #这里marker的尺寸和z的大小成正比
  23. ax.set_xlabel("X axis", fontdict=label_font)
  24. ax.set_ylabel("Y axis", fontdict=label_font)
  25. ax.set_zlabel("Z axis", fontdict=label_font)
  26. ax.set_title("Scatter plot", alpha=0.6, color="b", size=25, weight='bold', backgroundcolor="y") #子图的title
  27. ax.legend(loc="upper left") #legend的位置左上
  28. plt.show()
  • 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

Surface plot

  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from mpl_toolkits.mplot3d import Axes3D
  5. from matplotlib import cm
  6. from matplotlib.ticker import LinearLocator, FormatStrFormatter
  7. fig = plt.figure(figsize=(16,12))
  8. ax = fig.gca(projection="3d")
  9. # 准备数据
  10. x = np.arange(-5, 5, 0.25) #生成[-5,5]间隔0.25的数列,间隔越小,曲面越平滑
  11. y = np.arange(-5, 5, 0.25)
  12. x, y = np.meshgrid(x,y) #格点矩阵,原来的x行向量向下复制len(y)次,形成len(y)*len(x)的矩阵,即为新的x矩阵;原来的y列向量向右复制len(x)次,形成len(y)*len(x)的矩阵,即为新的y矩阵;新的x矩阵和新的y矩阵shape相同
  13. r = np.sqrt(x ** 2 + y ** 2)
  14. z = np.sin(r)
  15. surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm) # cmap指color map
  16. # 自定义z轴
  17. ax.set_zlim(-1, 1)
  18. ax.zaxis.set_major_locator(LinearLocator(20)) # z轴网格线的疏密,刻度的疏密,20表示刻度的个数
  19. ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) # 将z的value字符串转为float,保留2位小数
  20. #设置坐标轴的label和标题
  21. ax.set_xlabel('x',size=15)
  22. ax.set_ylabel('y',size=15)
  23. ax.set_zlabel('z',size=15)
  24. ax.set_title("Surface plot", weight='bold', size=20)
  25. #添加右侧的色卡条
  26. fig.colorbar(surf, shrink=0.6, aspect=8) # shrink表示整体收缩比例,aspect仅对bar的宽度有影响,aspect值越大,bar越窄
  27. plt.show()
  • 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

Contour plot

  1. # -*- coding: utf-8 -*-
  2. from mpl_toolkits.mplot3d import axes3d
  3. import matplotlib.pyplot as plt
  4. from matplotlib import cm
  5. fig = plt.figure(figsize=(16, 12))
  6. ax = fig.add_subplot(111, projection='3d')
  7. X, Y, Z = axes3d.get_test_data(0.05) #测试数据
  8. cset = ax.contour(X, Y, Z, cmap=cm.coolwarm) #color map选用的是coolwarm
  9. #cset = ax.contour(X, Y, Z,extend3d=True, cmap=cm.coolwarm)
  10. ax.set_title("Contour plot", color='b', weight='bold', size=25)
  11. plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

以下两图分别是未设置extend3d属性和设置extend3d属性为True的轮廓图: 
 

  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from matplotlib import cm
  5. from mpl_toolkits.mplot3d import axes3d
  6. fig = plt.figure(figsize=(16, 12))
  7. ax = fig.gca(projection="3d") # get current axis
  8. X, Y, Z = axes3d.get_test_data(0.05) #测试数据
  9. ax.plot_surface(X, Y, Z, rstride=3, cstride=3, alpha=0.3)
  10. cset = ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)
  11. cset = ax.contour(X, Y, Z, zdir="x", offset=-40, cmap=cm.coolwarm)
  12. cset = ax.contour(X, Y, Z, zdir="y", offset=40, cmap=cm.coolwarm)
  13. ax.set_xlabel('X')
  14. ax.set_xlim(-40, 40)
  15. ax.set_ylabel('Y')
  16. ax.set_ylim(-40, 40)
  17. ax.set_zlabel('Z')
  18. ax.set_zlim(-100, 100)
  19. ax.set_title('Contour plot', alpha=0.5, color='g', weight='bold', size=30)
  20. plt.show()
  • 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

Bar plot

  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from mpl_toolkits.mplot3d import Axes3D
  5. fig = plt.figure(figsize=(16, 12))
  6. ax = fig.add_subplot(111, projection="3d")
  7. a = zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0])
  8. for c, z in a:
  9. xs = np.arange(20) # [0,20)之间的自然数,共20
  10. ys = np.random.rand(20) # 生成20个[0,1]之间的随机数
  11. cs = [c] * len(xs) # 生成颜色列表
  12. ax.bar(xs, ys, z, zdir='x', color=cs, alpha=0.8) # 以zdir='x',指定z的方向为x轴,那么x轴取值为[30,20,10,0]
  13. # ax.bar(xs, ys, z, zdir='y', color=cs, alpha=0.8)
  14. # ax.bar(xs, ys, z, zdir='z', color=cs, alpha=0.8)
  15. ax.set_xlabel('X')
  16. ax.set_ylabel('Y')
  17. ax.set_zlabel('Z')
  18. ax.set_title('Bar plot', size=25, weight='bold')
  19. plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

2D plot in 3D

  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from mpl_toolkits.mplot3d import Axes3D
  5. fig = plt.figure(figsize=(16, 12))
  6. ax = fig.gca(projection="3d")
  7. # 在x轴和y轴画sin函数
  8. x = np.linspace(0, 1, 100)
  9. y = np.sin(2 * np.pi * x) + 1 # 2*π*x∈[0,2π] y属于[0,2]
  10. ax.plot(x, y, zs=0, zdir='z', label="sin curve in (x,y)")
  11. colors = ('r', 'g', 'b', 'k')
  12. x = np.random.sample(20 * len(colors))
  13. y = np.random.sample(20 * len(colors))
  14. c_list = []
  15. for c in colors:
  16. c_list.append([c] * 20) # 比如,[colors[0]*5]的结果是['r','r','r','r','r'],是个list
  17. ax.scatter(x, y, zs=0, zdir='y', c=c_list, label="scatter points in (x,z)")
  18. ax.legend()
  19. ax.set_xlim(0, 1)
  20. ax.set_ylim(0, 2)
  21. ax.set_zlim(0, 1)
  22. ax.set_xlabel("X")
  23. ax.set_ylabel("Y")
  24. ax.set_zlabel("Z")
  25. ax.view_init(elev=20, azim=25) # 调整坐标轴的显示角度
  26. plt.show()
  • 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

Subplot

  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from matplotlib import cm
  5. from mpl_toolkits.mplot3d import axes3d
  6. from matplotlib.ticker import LinearLocator, FormatStrFormatter
  7. fig = plt.figure(figsize=plt.figaspect(0.5)) # figure的高度是宽度的0.5倍
  8. # 子图1
  9. ax = fig.add_subplot(121, projection="3d")
  10. X = np.arange(-5, 5, 0.25) # 生成的List的间隔为0.25
  11. Y = np.arange(-5, 5, 0.25)
  12. X, Y = np.meshgrid(X, Y)
  13. R = np.sqrt(X ** 2 + Y ** 2)
  14. Z = np.sin(R)
  15. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm)
  16. ax.set_zlim(-2, 2)
  17. ax.zaxis.set_major_locator(LinearLocator(20))
  18. ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
  19. fig.colorbar(surf, shrink=0.6, aspect=10)
  20. # 子图2
  21. ax = fig.add_subplot(122, projection="3d")
  22. X, Y, Z = axes3d.get_test_data(0.05)
  23. ax.plot_wireframe(X, Y, Z)
  24. plt.show()
  • 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

参考文献:mplot3d官方文档 
mplot3d官方API

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/237880
推荐阅读
相关标签
  

闽ICP备14008679号