matplotlib中subplot和axes创建子图的应用

转自:https://blog.csdn.net/claroja/article/details/70841382
刚开始用matplotlib时对其中的一些概念和继承关系一直不是很清楚,下面的内容会有帮助。

总括

MATLAB和pyplot有当前的图形(figure)和当前的轴(axes)的概念,所有的作图命令都是对当前的对象作用。可以通过gca()获得当前的axes(轴),通过gcf()获得当前的图形(figure)。
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

这里写图片描述
如果不指定figure()的轴,figure(1)命令默认会被建立,同样的如果你不指定subplot(numrows, numcols, fignum)的轴,subplot(111)也会自动建立。

import matplotlib.pyplot as plt
plt.figure(1) # 创建第一个画板(figure)
plt.subplot(211) # 第一个画板的第一个子图
plt.plot([1, 2, 3])
plt.subplot(212) # 第二个画板的第二个子图
plt.plot([4, 5, 6])
plt.figure(2) #创建第二个画板
plt.plot([4, 5, 6]) # 默认子图命令是subplot(111)
plt.figure(1) # 调取画板1; subplot(212)仍然被调用中
plt.subplot(211) #调用subplot(211)
plt.title('Easy as 1, 2, 3') # 做出211的标题

这里写图片描述

subplot()是将整个figure均等分割,而axes()则可以在figure上画图。

import matplotlib.pyplot as plt
import numpy as np
# 创建数据
dt = 0.001
t = np.arange(0.0, 10.0, dt)
r = np.exp(-t[:1000]/0.05) # impulse response
x = np.random.randn(len(t))
s = np.convolve(x, r)[:len(x)]*dt # colored noise
# 默认主轴图axes是subplot(111)
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')
#内嵌图
a = plt.axes([.65, .6, .2, .2], facecolor='y')
n, bins, patches = plt.hist(s, 400, normed=1)
plt.title('Probability')
plt.xticks([])
plt.yticks([])
#另外一个内嵌图
a = plt.axes([0.2, 0.6, .2, .2], facecolor='y')
plt.plot(t[:len(r)], r)
plt.title('Impulse response')
plt.xlim(0, 0.2)
plt.xticks([])
plt.yticks([])
plt.show()

这里写图片描述

你可以通过clf()清空当前的图板(figure),通过cla()来清理当前的轴(axes)。你需要特别注意的是记得使用close()关闭当前figure画板


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值