matplotlib绘制多个子图——subplot

来源:互联网 发布:fm2016中文版for mac 编辑:程序博客网 时间:2024/05/19 18:00

在matplotlib下,一个Figure对象可以包含多个子图(Axes),可以使用subplot()快速绘制,其调用形式如下:

subplot(numRows, numCols, plotNum)

图表的整个绘图区域被分成numRows行和numCols列,plotNum参数指定创建的Axes对象所在的区域,如何理解呢?

如果numRows = 3,numCols = 2,那整个绘制图表样式为3X2的图片区域,用坐标表示为(1,1),(1,2),(1,3),(2,1),(2,2),(2,3)。这时,当plotNum = 1时,表示的坐标为(1,3),即第一行第一列的子图;

import numpy as npimport matplotlib.pyplot as plt# 分成2x2,占用第一个,即第一行第一列的子图plt.subplot(221)# 分成2x2,占用第二个,即第一行第二列的子图plt.subplot(222)# 分成2x1,占用第二个,即第二行plt.subplot(212)plt.show()


[python] view plain copy
  1. import matplotlib.pyplot as plt  
  2. import numpy as np  
  3.   
  4.   
  5. # plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')  
  6. # plt.axis([0, 6, 0, 20])  
  7. # plt.show()  
  8.   
  9. # t = np.arange(0., 5., 0.2)  
  10. # plt.plot(t, t, 'r--', t, t ** 2, 'bs', t, t ** 3, 'g^')  
  11.   
  12.   
  13. def f(t):  
  14.     return np.exp(-t) * np.cos(2 * np.pi * t)  
  15.   
  16.   
  17. t1 = np.arange(050.1)  
  18. t2 = np.arange(050.02)  
  19.   
  20. plt.figure(12)  
  21. plt.subplot(221)  
  22. plt.plot(t1, f(t1), 'bo', t2, f(t2), 'r--')  
  23.   
  24. plt.subplot(222)  
  25. plt.plot(t2, np.cos(2 * np.pi * t2), 'r--')  
  26.   
  27. plt.subplot(212)  
  28. plt.plot([1234], [14916])  
  29.   
  30. plt.show()  

原创粉丝点击