使用matplotlib.pyplot中的三种方法画子图

本文所用包:

from matplotlib import pyplot as plt

import numpy as np

此文主要记录使用matplotlib.pyplot中的三个函数,主要结合代码展示效果:

一、plt.subplots

实例代码:

 1 from matplotlib import pyplot as plt
 2 import numpy as np
 3 
 4 x = np.linspace(1, 100, num= 25, endpoint = True)
 5 
 6 def y_subplot(x,i):
 7     return np.cos(i * np.pi *x)
 8 
 9 #使用subplots 画图
10 f, ax = plt.subplots(2,2)
11 #type(f) #matplotlib.figure.Figure
12 
13 style_list = ["g+-", "r*-", "b.-", "yo-"]
14 ax[0][0].plot(x, y_subplot(x, 1), style_list[0])
15 ax[0][1].plot(x, y_subplot(x, 2), style_list[1])
16 ax[1][0].plot(x, y_subplot(x, 3), style_list[2])
17 ax[1][1].plot(x, y_subplot(x, 4), style_list[3])
18 
19 plt.show()

注释:使用subplots会返回两个东西,一个是matplotlib.figure.Figure,也就是f,另一个是Axes object or array of Axes objects,也就是代码中的ax;

把f理解为你的大图,把ax理解为包含很多小图对象的array;所以下面的代码就使用ax[0][0]这种从ax中取出实际要画图的小图对象;画出的图如下所示;

二、plt.subplot;

扫描二维码关注公众号,回复: 1777413 查看本文章

实例代码:

#使用subplot画图
for i in  range(1,5):
    plt.subplot(2,2,i)
    plt.plot(x, y_subplot(x,i), style_list[i- 1])
plt.show()

plt.subplot函数的第一个参数和第二个参数分别制定了子图有几列和几行;这个和subplots的参数意思相同;第三个参数就是指定在那个子图上画图的顺序,分别是从左往右;慢慢体味subplot和subplots的区别吧;subplot方法画的图如下所示:

 

三、plt.add_subplots

实例代码:

fig = plt.figure()
for i in range(1,5):
    ax = fig.add_subplot(2,2,i)
    ax.plot(x, y_subplot(x,i), style_list[i -1])

plt.show()

add_subplot函数也就是向Figure画板中添加每一个子图

画出的图形如下所示:

猜你喜欢

转载自www.cnblogs.com/nobbyoucanyouup/p/9239943.html