当前位置:   article > 正文

Matplotlib绘制三维图实现图形旋转、颜色变换和视频及动画输出_matplotlib三维视角旋转

matplotlib三维视角旋转

1. Matplotlib绘制三维图

通过Matplotlib.pyplot.axes.plot_surface来绘制一个三维曲面,代码如下:

  1. # -*_ coding: utf-8 -*-
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. x = np.linspace(-6, 6, 240)
  5. y = np.linspace(-6, 6, 240)
  6. X, Y = np.meshgrid(x, y)
  7. Z = np.sin(np.sqrt(X**2+Y**2))*2
  8. fig = plt.figure(figsize=(13, 10))
  9. ax3d = plt.axes(projection='3d')
  10. ax3d.set_xlabel("X")
  11. ax3d.set_ylabel("Y")
  12. ax3d.set_zlabel("Z")
  13. ax3d.set_zlim(-3.01, 3.01)
  14. ax3d.set_xlim(-6.01, 6.01)
  15. ax3d.set_ylim(-6.01, 6.01)
  16. plt.tick_params(labelsize=10)
  17. surf = ax3d.plot_surface(X, Y, Z, cmap = plt.cm.YlGnBu_r)
  18. ax3d.set_title(r"Surface Z = 3sin($\sqrt{X^2 + y^2})$", fontsize=18)
  19. fig.colorbar(surf, shrink=0.5, aspect=20)
  20. plt.tight_layout() #减少窗口空白
  21. plt.show()

2. 实现三维图形的旋转

Matplotlib.pyplot.axes.view_init()可以设置三维图形的视角,所有可以通过视角的变化来实现三维图形的旋转,代码如下:

  1. for angle in range(0, 360):
  2. ax3d.view_init(30, angle)
  3. plt.draw()
  4. plt.pause(0.1)

其中,view_init()的第一个参数是上下视角旋转角度,第二个参数是x,y平面视角旋转角度。

3.实现三维图形颜色的变换

 Matplotlib.colors.LinearSegmentedColormap可以使用颜色数列自定义cmap颜色,使用surf.set_cmap()和plt.setp()可以更改三维图形曲面和网格的颜色。这样通过对颜色数列的移位,就可实现颜色的变换了,代码如下:

  1. from matplotlib.colors import LinearSegmentedColormap
  2. clist = [(26/255, 49/255, 139/255), (73/255, 108/255, 206/255), (130/255, 170/255, 231/255),
  3. (185/255, 210/255, 243/255), (230/255, 240/255, 254/255), (249/255, 219/255, 229/255),
  4. (247/255, 166/255, 191/255), (228/255, 107/255, 144/255), (192/255, 63/255, 103/255),
  5. (154/255, 19/255, 61/255)] # 颜色数值需在0和1之间
  6. mycmp = LinearSegmentedColormap.from_list("No001", clist)
  7. for angle in range(0, 360):
  8. ax3d.view_init(30, angle)
  9. clist = clist[-1:] + clist[:-1] #颜色列表向左移一位
  10. mycmp = LinearSegmentedColormap.from_list("No001", clist)
  11. plt.setp(surf, color=clist[-1])
  12. surf.set_cmap(mycmp)
  13. plt.draw()
  14. plt.pause(0.1)

4. 三维效果的视频输出

Matplotlib.animation.FFMpegWriter利用FFMpeg实现视频的输出,首先需要安装FFMpeg程序,如果程序找不到ffmpeg.exe文件,会报错“找不到系统文件”,需要使用plt.rcParams来指定文件位置。最后,调用cmd,使用ffmpeg给得到的视频添加上音乐。

  1. from matplotlib.animation import FFMpegWriter
  2. import os
  3. plt.rcParams['animation.ffmpeg_path'] ='C:\\ffmpeg\\bin\\ffmpeg.exe'
  4. metadata = dict(title='Rotating', artist='Matplotlib', comment='Rotating Video')
  5. writer = FFMpegWriter(fps=10, metadata=metadata, extra_args=['-vcodec', 'libx264'])
  6. file_dir = 'D:\\works\\Python_Qt\\matplotlib_figs\\video\\'
  7. with writer.saving(fig, file_dir+'out1_ffmpeg.mp4', 120):
  8. for angle in range(0, 360):
  9. ax3d.view_init(30, angle)
  10. clist = clist[-1:] + clist[:-1] #颜色列表向左移一位
  11. mycmp = LinearSegmentedColormap.from_list("No001", clist)
  12. plt.setp(surf, color=clist[-1])
  13. surf.set_cmap(mycmp)
  14. plt.draw()
  15. writer.grab_frame()
  16. plt.pause(0.1)
  17. cmd = "C:\\ffmpeg\\bin\\ffmpeg.exe -i %s -i %s %s" % (file_dir+'music.mp3', file_dir+'out1_ffmpeg.mp4', file_dir+'out1_ffmpeg_music.mp4')
  18. os.system(cmd)

其中,grab_frame()用来抓取窗口内容

5. 三维效果的动画输出

Matplotlib.animation.PillowWriter利用Pillow实现gif动画的输出,代码和视频输出类似:

  1. from matplotlib.animation import PillowWriter
  2. metadata = dict(title='Rotating', artist='Yisl04', comment='Rotating Video')
  3. writer = PillowWriter(fps=10, metadata=metadata)
  4. with writer.saving(fig, file_dir+'out1_pillow.gif', 120):
  5. for angle in range(0, 360):
  6. ax3d.view_init(30, angle)
  7. clist = clist[-1:] + clist[:-1] #颜色列表向左移一位
  8. mycmp = LinearSegmentedColormap.from_list("No001", clist)
  9. plt.setp(surf, color=clist[-1])
  10. surf.set_cmap(mycmp)
  11. plt.draw()
  12. writer.grab_frame()
  13. plt.pause(0.1)

最后,整合上述代码:

  1. # -*_ coding: utf-8 -*-
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from matplotlib.animation import FFMpegWriter
  5. from matplotlib.colors import LinearSegmentedColormap
  6. clist = [(26/255, 49/255, 139/255), (73/255, 108/255, 206/255), (130/255, 170/255, 231/255),
  7. (185/255, 210/255, 243/255), (230/255, 240/255, 254/255), (249/255, 219/255, 229/255),
  8. (247/255, 166/255, 191/255), (228/255, 107/255, 144/255), (192/255, 63/255, 103/255),
  9. (154/255, 19/255, 61/255)] # 颜色数值需在0和1之间
  10. mycmp = LinearSegmentedColormap.from_list("No001", clist)
  11. x = np.linspace(-6, 6, 240)
  12. y = np.linspace(-6, 6, 240)
  13. X, Y = np.meshgrid(x, y)
  14. Z = np.sin(np.sqrt(X**2+Y**2))*2
  15. fig = plt.figure(figsize=(13, 10))
  16. ax3d = plt.axes(projection='3d')
  17. ax3d.set_xlabel("X")
  18. ax3d.set_ylabel("Y")
  19. ax3d.set_zlabel("Z")
  20. ax3d.set_zlim(-3.01, 3.01)
  21. ax3d.set_xlim(-6.01, 6.01)
  22. ax3d.set_ylim(-6.01, 6.01)
  23. plt.tick_params(labelsize=10)
  24. surf = ax3d.plot_surface(X, Y, Z, cmap = mycmp)
  25. ax3d.set_title(r"Surface Z = 3sin($\sqrt{X^2 + y^2})$", fontsize=18)
  26. #shrink表示图例缩放比例,aspect表示长宽比
  27. fig.colorbar(surf, shrink=0.5, aspect=20)
  28. plt.tight_layout() #减少窗口空白
  29. #定义视频和动画输出函数
  30. def video_output(video_format, clist):
  31. file_dir = 'D:\\works\\Python_Qt\\matplotlib_figs\\video\\'
  32. if video_format == 'ffmpeg':
  33. plt.rcParams['animation.ffmpeg_path'] ='C:\\ffmpeg\\bin\\ffmpeg.exe'
  34. metadata = dict(title='Rotating', artist='matplotlib', comment='Rotating Video')
  35. writer = FFMpegWriter(fps=10, metadata=metadata, extra_args=['-vcodec', 'libx264'])
  36. with writer.saving(fig, file_dir+'out1_ffmpeg.mp4', 120):
  37. for angle in range(0, 360):
  38. ax3d.view_init(30, angle)
  39. clist = clist[-1:] + clist[:-1] #颜色列表向左移一位
  40. mycmp = LinearSegmentedColormap.from_list("No001", clist)
  41. plt.setp(surf, color=clist[-1])
  42. surf.set_cmap(mycmp)
  43. plt.draw()
  44. writer.grab_frame()
  45. plt.pause(0.1)
  46. cmd = "C:\\ffmpeg\\bin\\ffmpeg.exe -i %s -i %s %s" % (file_dir+'music.mp3', file_dir+'out1_ffmpeg.mp4', file_dir+'out1_ffmpeg_music.mp4')
  47. os.system(cmd)
  48. elif video_format == 'pillow':
  49. metadata = dict(title='Rotating', artist='matplotlib', comment='Rotating Video')
  50. writer = PillowWriter(fps=10, metadata=metadata)
  51. with writer.saving(fig, file_dir+'out1_pillow.gif', 120):
  52. for angle in range(0, 360):
  53. ax3d.view_init(30, angle)
  54. clist = clist[-1:] + clist[:-1] #颜色列表向左移一位
  55. mycmp = LinearSegmentedColormap.from_list("No001", clist)
  56. plt.setp(surf, color=clist[-1])
  57. surf.set_cmap(mycmp)
  58. plt.draw()
  59. writer.grab_frame()
  60. plt.pause(0.1)
  61. else:
  62. ax3d.set_title(r"视频输出格式错误!", fontsize=18, color='red')
  63. plt.show()
  64. #输出视频
  65. video_output('ffmpeg', clist)
  66. #输出动画
  67. video_output('pillow', clist)

得到的视频和动画如下所示:

Matplotlib绘制三维图实现图形旋转、颜色变换


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
  

闽ICP备14008679号