脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 一个figure上显示多个图像的实例

python 一个figure上显示多个图像的实例

2021-08-03 00:41gaoxiaobai666666 Python

今天小编就为大家分享一篇python 一个figure上显示多个图像的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

方法一:主要是inshow()函数的使用

首先基本的画图流程为:

  1. import matplotlib.pyplot as plt
  2.  
  3. #创建新的figure
  4. fig = plt.figure()
  5.  
  6. #必须通过add_subplot()创建一个或多个绘图
  7. #ax = fig.add_subplot(221)
  8.  
  9. #绘制2x2两行两列共四个图,编号从1开始
  10. ax1 = fig.add_subplot(221)
  11. ax2 = fig.add_subplot(222)
  12. ax3 = fig.add_subplot(223)
  13. ax4 = fig.add_subplot(224)
  14.  
  15. #图片的显示
  16. plt.show()

然后就会有四个在同一张图上的figure

python 一个figure上显示多个图像的实例

然后我们可以用python中的Matplotlib库中的,imshow()函数实现绘图。imshow()可以用来绘制热力图

  1. #coding=utf-8
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4.  
  5. points = np.arange(-5,5,0.01)
  6.  
  7. xs,ys = np.meshgrid(points,points)
  8.  
  9. z = np.sqrt(xs**2 + ys**2)
  10.  
  11. #创建新的figure
  12. fig = plt.figure()
  13.  
  14. #绘制2x2两行两列共四个图,编号从1开始
  15. ax = fig.add_subplot(221)
  16. ax.imshow(z)
  17.  
  18. ax = fig.add_subplot(222)
  19. #使用自定义的colormap(灰度图)
  20. ax.imshow(z,cmap=plt.cm.gray)
  21.  
  22. ax = fig.add_subplot(223)
  23. #使用自定义的colormap
  24. ax.imshow(z,cmap=plt.cm.cool)
  25.  
  26. ax = fig.add_subplot(224)
  27. #使用自定义的colormap
  28. ax.imshow(z,cmap=plt.cm.hot)
  29.  
  30. #图片的显示
  31. plt.show()

python 一个figure上显示多个图像的实例

方法二:subplot的使用,在python中,可以用subplot绘制子图。

常用方法:pl.subplot(121)第一个1代表1行,第二个2代表两列,第三个1代表第一个图。

  1. # -*- coding: utf-8 -*-
  2. """
  3. 演示二维插值。
  4. """
  5. import numpy as np
  6. from scipy import interpolate
  7. import pylab as pl
  8. import matplotlib as mpl
  9.  
  10. def func(x, y):
  11. return (x+y)*np.exp(-5.0*(x**2 + y**2))
  12.  
  13. # X-Y轴分为15*15的网格
  14. y,x= np.mgrid[-1:1:15j, -1:1:15j]
  15.  
  16. fvals = func(x,y) # 计算每个网格点上的函数值 15*15的值
  17. print len(fvals[0])
  18.  
  19. #三次样条二维插值
  20. newfunc = interpolate.interp2d(x, y, fvals, kind='cubic')
  21.  
  22. # 计算100*100的网格上的插值
  23. xnew = np.linspace(-1,1,100)#x
  24. ynew = np.linspace(-1,1,100)#y
  25. fnew = newfunc(xnew, ynew)#仅仅是y 100*100的值
  26.  
  27. # 绘图
  28. # 为了更明显地比较插值前后的区别,使用关键字参数interpolation='nearest'
  29. # 关闭imshow()内置的插值运算。
  30. pl.subplot(121)
  31. im1=pl.imshow(fvals, extent=[-1,1,-1,1], cmap=mpl.cm.hot, interpolation='nearest', origin="lower")#pl.cm.jet
  32. #extent=[-1,1,-1,1]为x,y范围 favals为
  33. pl.colorbar(im1)
  34.  
  35. pl.subplot(122)
  36. im2=pl.imshow(fnew, extent=[-1,1,-1,1], cmap=mpl.cm.hot, interpolation='nearest', origin="lower")
  37. pl.colorbar(im2)
  38.  
  39. pl.show()

以上的代码为二维插值中画图的演示。绘图如下:

python 一个figure上显示多个图像的实例

以上这篇python 一个figure上显示多个图像的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/gaoxiaobai666666/article/details/86308278

延伸 · 阅读

精彩推荐