10.Matplotlib绘图--子图

本篇有参考如下博客,对原作者表示十分感谢:

https://blog.csdn.net/claroja/article/details/70841382

https://www.jianshu.com/p/de223a79217a

很多时候需要把多幅图放一起观测更加直观,  Matplotlib可以实现在一个大图(figure)中存放多个子图(axes),主要方法有subplot(), subplots().

pylot中,所有的绘图都是对当前对象作用,包括当前图形(figure)和当前坐标轴(axes),可以通过gca()获得当前axes, 通过gcf()获得当前figure.

如果不指定figure(),figure(1)会默认建立,同样如果不指定subplot(numrows,numcols,fignum),subplot(1,1,1)自动被建立;

1.创建多个figure图

默认创建一个子图;

t2 = np.arange(0.0,2*np.pi,0.02)

plt.figure()

plt.plot(t2,np.sin(t2),'k')

plt.show()

创建两个figure

import matplotlib.pyplot as plt
import numpy as np

def f(t):
    return np.exp(-t)*np.cos(2*np.pi*t)

t1 = np.arange(0.0,2*np.pi,0.1)
t2 = np.arange(0.0,2*np.pi,0.02)

fig1 = plt.figure()
plt.plot(t2,np.sin(t2),'k')
plt.title(r'$figure1$',fontsize=30)

fig2 = plt.figure(2)
plt.plot(t1,f(t1),'b')
plt.title(r'$figure2$',fontsize=30)
plt.show()

2. subplot(): 在一个大图(Figure)里创建多个子图(Axes):

plt.plot(t1,f(t1),'bo',t2,f(t2),'g')

plt.subplot(212)
#plt.plot(t2,np.cos(2*np.pi*t2),'r--')

fig = plt.gcf()
fig.set_size_inches(3,3) #改变整个figure大小

ax = plt.gca() #获取当前axes
ax.plot(t2,np.cos(2*np.pi*t2),'r--')

plt.show()

3.subplots():一次性创建多个子图(Axes)

t = np.arange(0,2.2,0.1)
s = np.sin(t*np.pi)

#直接一次性创建多个subplot
fig,ax = plt.subplots(2,2)

ax[0][0].plot(t,s,'r*')

plt.show()

t = np.arange(0,2.2,0.1)
s = np.sin(t*np.pi)

fig,ax = plt.subplots(2,2)

ax[0][0].plot(t,s,'r*')
ax[1][1].plot(t*2,s,'b--')

plt.show()

4.在一个大图(一个figure只包含一个axes)中实现多个小图

先创建一个大图,只包含一个axes

plt.axes((left,bottom,width,height), facecolor='w)

(left,bottom,width,height):分别为子图的左下坐标,以及相对整个大图的宽高(范围0~1)

import matplotlib.pyplot as plt
import numpy as np

dt = 0.001
t = np.arange(0.0,10.0,dt)
r = np.exp(-t[:len(t)]/0.05)
x = np.random.randn(len(t))
s = np.convolve(x,r)[:len(x)]*dt

plt.plot(t,s)
plt.axis([0,1,1.1*np.amin(s),2*np.amax(s)])

plt.xlabel('time(s)')
plt.ylabel('current(nA)')
plt.title('Gaussian colored noise')

plt.show()

添加一个新子图

a = plt.axes([0.65,.6,0.2,0.2],facecolor='y')
n,bins,patches = plt.hist(s,400,normed=1)
plt.title('Probability')

再添加一个子图

b = plt.axes([0.2,0.6,.2,.2],facecolor='b')
plt.plot(t[:len(r)],r)
plt.title('Impulse response')
plt.xlim(0,0.2)

#去掉坐标轴刻度
plt.xticks([])
plt.yticks([])
plt.show()

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值