Matplotlib库

Matplotlib库的入门

python优秀的数据可视化第三方库,Matplotlib库由各种可视化类构成,内部结构复杂。Matplotlib提供了一个子库——matplotlib.pyplot是绘制各类可视化图像的命令子库,相当于matplotlib的快捷方式

matplotlib库的使用   

import matplotlib.pyplot as plt   (plt为引入模块的别名)

pyplot的绘图区域

plt.subplot(nrows,ncols,plot_number)  nrows为行数,ncols为列数,plot_number为位置

np.exp(x)、np.cos(x)为Numpy的一元函数,计算数组各元素的指数值、余弦值。

pyplot的plot( )函数

plt.plot(x,y,format_string,**kwargs) x为x轴数据,y为y轴数据

format_string为曲线类型字符串,由颜色字符、风格字符和标记字符组成。,'--'虚线,'-'实线,':'点线,'g'绿色,'b'蓝色,'o'坐标点实心圈标记符,'*'星形标记符,线条颜色标记符可混合随意搭配,如'--r*'; 控制颜色:color='green';线条风格:linestyle='dashed';标记风格:marker='o';标记颜色:arkerfacecolor='blue';标记尺寸:markersize=20      

**kwargs为其他组(x,y,format_string)——同时显示多条曲线

plt.plot(distance,lt,'orange',distance,lcsr,'gray',\
         distance,ltmin,'blue',distance,ltmax,'green')
#可以将其拆为4段,作用相同
a = plt.plot(distance,lt,'orange')
b = plt.plot(distance,lcsr,'gray')
c = plt.plot(distance,ltmin,'blue')
d = plt.plot(distance,ltmax,'green')

 

pyplot的中文显示

pyplot不默认支持中文显示,包括两种方法:

1.用rcParams修改字体(把绘图区域的所有字体变成新的字体)

matplotlib.rcParams[' font.family/font.style/font.size '] = '  '  包括字体、字体风格(正体/斜体)、字体大小

2.在有中文输出的地方,增加属性fontproperties(修改局部字体)

plt.xlabel('横轴:时间',fontproperties='SimHei',fontsize=20)

pyplot的文本显示

plt.xlabel():对x轴增加文本;plt.ylabel():对y轴增加文本;plt.title():对图形整体增加文本;

plt.text(x,y,string,fontsize,va,ha,rotation)在任意位置增加文本,x,y文本起始位置坐标、string文本内容、fontsize字体大小、va垂直对齐方式( 'va='center'/ 'top' / 'bottom' /'baseline' )、ha水平对齐方式( ha='center'/'right'/'left' )、rotation倾斜角度(rotation=15)如plt.text(1,5,'我喜欢你!',ha='left',rotation=15)

plt.grid()/plt.grid(1)/plt.grid(True)显示网格线plt.grid(axis='x'):只显示y轴上的网格线;plt.grid(axis='x')/plt.grid(1,axis='x')/plt.grid(True,axis='x'):只显示x轴上的网格线(竖条的)

plt.axis([a, b, c, d]):设置x轴的范围为[a, b],y轴的范围为[c, d]

plt.annotate(s,xy,xytext,arrowprops=dict()):在图形中增加带箭头的注解

pyplot的高级绘图区域 

plt.subplot2grid(GridSpec,CurSpec,colspan=1,rowspan=1 ) 先粗后细再连接

 plt.subplot2grid( )每次都需要给出(3,3)方位,可用GridSpec类 + subplot( ) 简化设计。

pyplot添加图例

plt.legend(handles,labels,loc,prop) 函数实现,包括两个list参数,第一个list 参数(handles 参数)用于引用折线图上的每条折线;第二个 list 参数(labels)代表为每条折线所添加的图例。 prop 属性指定使用中文字体。handles参数可不写,只传入 labels 参数,这样该 labels 参数将按顺序为折线图中的多条折线添加图例。

loc为图例添加位置。'best':自动选择最佳位置。'upper right':将图例放在右上角。'upper left':左上角。'lower left':左下角。'lower right':右下角。'right':右边。'center left':左边居中位置。'center right':右边居中位置。'lower center':底部居中位置。'upper center':顶部居中位置。'center':中心位置。

a = plt.plot(distance,lt,'orange')
b = plt.plot(distance,lcsr,'gray')
c = plt.plot(distance,ltmin,'blue')
d = plt.plot(distance,ltmax,'green')
#plt.plot(distance,lt,'orange',distance,lcsr,'gray',distance,ltmin,'blue',distance,ltmax,'green')    
plt.xlabel('距离/km',fontproperties='SimHei',fontsize=15)
plt.ylabel('L(t)',fontsize=15)
plt.legend(labels=['L(t)','L(csr)','L(t)min','L(t)max'])
plt.show()

pyplot保存图片

plt.savefig('k.png',bbox_inches='tight'),第一个参数为保存图片的名称,第二个参数表示去除多余区域。!plt.savefig()不能与plt.show()同时使用,否则会保存失败。使用plt.savefig()也可以看到图片。



Matplotlib基础绘图函数

pyplot饼图的绘制  plt.pie( )

pyplot直方图的绘制 plt.hist( )

pyplot极坐标的绘制(面向对象绘制)

import numpy as np
import matplotlib.pyplot as plt

N = 20 #数据个数
theta = np.linspace(0.0,2*np.pi,N,endpoint=False) #0-360度,等分N个角度
radii = 10*np.random.rand(N)   #生成每个角度对应的值 
width = np.pi/4*np.random.rand(N)  #得到宽度值 创建随机数组 0-1 均匀分布的浮点数

ax = plt.subplot(111,projection='polar') #一个绘图区域
bars = ax.bar(theta,radii,width=width,bottom=0.0)   #基于对象的绘图,某个位置,长度 ,宽度

for r,bar in zip(radii,bars):
    bar.set_facecolor(plt.cm.viridis(r/10.))
    bar.set_alpha(0.5)
    
plt.show()

 

pyplot散点图的绘制(面向对象方法)

import numpy as np
import matplotlib.pyplot as plt

fig,ax = plt.subplots()  #将函数变为对象,图表,图表区域,若为空则默认为111
ax.plot(10*np.random.randn(100),10*np.random.randn(100),'o') #绘制点,randn生成正态分布的100个值,*10扩散
ax.set_title('Simple Scatter')  #对象的方法

plt.show()

Matplotlib引力波的绘制

引力波:爱因斯坦基于广义相对论预言了引力波的存在,2016年探测到引力波信号。物理学中,引力波是因为时空弯曲,对外以辐射形式传播的能量。

绘制最原始的引力波和理想引力波

数据源:http://python123.io/dv/grawave.html(数据文件要存储在与py文件相同的文件夹里/用绝对路径

http://python123.io/dv/H1_Strain.wav .wav文件:声音文件,真实引力波数据;http://python123.io/dv/L1_Strain.wav

http://python123.io/dv/wf_template.txt .txt文件:由科学家生成的作为对比的引力波模板文件

#产生时间序列,从配置文档中读取时间相关数据
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile    #读取波形文件的库

rate_h,hstrain = wavfile.read(r"H1_Strain.wav","rb")    #wavfile.read()读取下载的音频文件,read读取的结果赋值给速率rate和数据strain
rate_l,lstrain = wavfile.read(r"L1_Strain.wav","rb")    #当文件名中出现反斜杠等特殊字符时,字符串前加r表示原始字符串,
reftime,ref_H1 = np.genfromtxt('wf_template.txt').transpose() 
#reftime为时间序列,np.genfromtxt执行两个运算循环:将文件每行转为字符串序列、将字符串序列转为相应的数据类型,读取为两行的矩阵,transpose先转置再对两个变量赋值

#读取应变数据
htime_interval = 1/rate_h    #波形的时间间隔,rate变量的倒数
ltime_interval = 1/rate_l

htime_len = hstrain.shape[0]/rate_h   #strain为数据矩阵,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)   #以原点为中心的对称图像

#绘制H1 Strain
fig = plt.figure(figsize=(12,6))   #figsize设置图像大小,长12宽6

plth = fig.add_subplot(221)       #2*2个子图,第一个子图中绘图
plth.plot(htime,hstrain,'y')      #时间为x轴,应变数据为y轴,黄色绘制曲线
plth.set_xlabel('Time (seconds)')
plth.set_ylabel('H1 Strain')
plth.set_title('H1 Strain')

#绘制L1 Strain & Temple
pltl = fig.add_subplot(222)      #绘图区域第一列右边

pltl.plot(ltime,lstrain,'g')
pltl.set_xlabel('Time (seconds)')
pltl.set_ylabel('L1 Strain')
pltl.set_title('L1 Strain')

pltref = fig.add_subplot(212)    #绘图区域第二列

pltref.plot(reftime,ref_H1)
pltref.set_xlabel('Time (seconds)')
pltref.set_ylabel('Temple Strain')
pltref.set_title('Template')
fig.tight_layout()

#显示并保存图像
fig.tight_layout()       #自动调整图像外部边缘

plt.savefig("Gravitational_Waves_Original.png")
plt.show()
plt.close(fig)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值