引力波实例

参考代码

#引力波实例
import matplotlib.pyplot as plt 
import numpy as np
from scipy.io import wavfile

rate_h,hstrain=wavfile.read(r'C:\Users\Administrator\Desktop\H1_Strain.wav','rb')  #wavefile.read读取下载好的音频文件  前面加r 表示原始字符串
rate_l,lstrain=wavfile.read(r'C:\Users\Administrator\Desktop\L1_Strain.wav','rb')
reftime, ref_H1 =np.genfromtxt(r'C:\Users\Administrator\Desktop\wf_template.txt').transpose() 
 #文件每一行转换成字符串序列 将每个字符串序列转换成相应数据类型 则genfromtxt读取出来的是两行 的矩阵    transpose表示转置

htime_interval=1/rate_h #求倒数 得到波形的时间间隔
ltime_interval=1/rate_l

htime_len=hstrain.shape[0]/rate_h  #hstarin shape[0]表示读取第一维度的长度即数据点的个数 个数/rate 得到总长度
htime=np.arange(-htime_len/2,htime_len/2,htime_interval) #原点对称
ltime_len=lstrain.shape[0]/rate_l
ltime=np.arange(-ltime_len/2,ltime_len/2,ltime_interval)

fig=plt.figure(figsize=(12,6))  #大小为12*6的绘图空间

plth=fig.add_subplot(221)  #在子绘图区域 1 绘图   回忆:subplot第三个数 从左到右从上到下 1开始
plth.plot(htime,hstrain,'y')  #y表示黄颜色绘制曲线
plth.set_xlabel('Time(seconds)')
plth.set_ylabel('H1 strain')
plth.set_title('H1 Strain')

pltl=fig.add_subplot(222)
pltl.plot(ltime,lstrain,'g')
pltl.set_xlabel('Time')
pltl.set_ylabel('L1 strain')
pltl.set_title('L1 strain')

pltref=fig.add_subplot(212)  #两行一列 第二个
pltref.plot(reftime,ref_H1)
pltref.set_xlabel('Time')
pltref.set_ylabel('Template Strain')
pltref.set_title('Template')
fig.tight_layout()

plt.savefig('Gravitational_Waves_Original3(without layout).png')
plt.show()
plt.close(fig)

在这里插入图片描述

作者代码(仅绘图子区域方法不同、对于WAV的处理同上)
疑问:利用subplot2grid方法 如何调整绘图空间大小

plth=plt.subplot2grid((2,2),(0,0))
plth.plot(htime,hstrain,'r')
plth.set_xlabel('Time(seconds)')
plth.set_ylabel('H1 strain')
plth.set_title('H1 strain')

pltr=plt.subplot2grid((2,2),(0,1))
pltr.plot(ltime,lstrain)
pltr.set_xlabel('Time(seconds)')
pltr.set_ylabel('L1 strain')
pltr.set_title('L1 strain')

pltref=plt.subplot2grid((2,2),(1,0),colspan=2)
pltref.plot(reftime,ref_H1)
pltref.set_xlabel('Time')
pltref.set_ylabel('Template Strain')
pltref.set_title('Template')

plt.tight_layout()

plt.savefig('Gravitational_Waves_Original4.png')
plt.show()
plt.close()

在这里插入图片描述
从此实例中得到的新知识

  1. fig.tight_layout() 自动调整子图参数,使其充满整个图像区域,但需要fig是figure对象。若用subplot2grid()则返回的是axes对象,此时使用plt.tight_layout()即可
  2. 利用scipy.io的wavfile读取wav格式文件(常见音频文件),wavefile.read() 返回样本率和数据
  3. plt.close() close a figure window在用循环的时候必须加上此行。引申plt.clf() 清除图形及轴,可以直接用于其他绘图
  4. plt.savefig(’.png’)保存图像
  5. np.genfromtxt()用于进行两个循环 第一个循环将文件每一行转换成字符串序列 第二个循环将字符串序列转换为相应的数据类型(补充:.transpose()转置)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值