欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python画图1:matplotlib绘制两个变量相关性图详解

程序员文章站 2022-04-03 22:41:17
...

python画图1:matplotlib绘制两个变量相关性图详解

import numpy as np
import matplotlib.pyplot as plt

# 让每次生成的随机数一样,seed括号里的数用做标记没有实际含义
np.random.seed(19680801)

dt = 0.01
# np.arange()用法,函数返回一个有终点和起点的固定步长的排列,
# 第一个参数为起点,第二个参数为终点,第三个参数为步长
t = np.arange(0, 30, dt)
# print(t)
# randn函数返回一个或一组样本,具有标准正态分布,
# 函数括号里(5)表示1*5,(2,3)表示一个2*3的数组,(2,2,3)表示两个2*3的数组
nse1 = np.random.randn(len(t))                 # white noise 1
nse2 = np.random.randn(len(t))                 # white noise 2
# print(nse1)
# 两组数据,数据构成由arange排列的sin和一个随机数构成
s1 = np.sin(2 * np.pi * 10 * t) + nse1
s2 = np.sin(2 * np.pi * 10 * t) + nse2
# 将返回既是fig图形对象又axes是2x1的轴对象数组,也就是两行一列的两个子图
fig, axs = plt.subplots(2, 1) # 和以下三句等同
# fig=plt.figure()
# ax=fig.add_subplot(2,1,1)
# ax=fig.add_subplot(2,1,2)

# axs[0]表示第一个图
axs[0].plot(t, s1, t, s2)
# 设置x轴起始和结束坐标
axs[0].set_xlim(0, 2)
# x和y标签
axs[0].set_xlabel('time')
axs[0].set_ylabel('s1 and s2')
# grid(true)绘制刻度线的网格 False不绘制
axs[0].grid(True)

# axs[1]表示第二个图 dt为步长
# 绘制s1和s2相关性函数,NNFT=256应该是默认参数
cxy, f = axs[1].cohere(s1, s2, 256, 1. / dt)
# 设置y坐标为相关性
axs[1].set_ylabel('coherence')

#tight_layout会自动调整子图参数,使之填充适应整个图像区域
fig.tight_layout()
# savefig()保存图片,注意路径为反斜杠
plt.savefig('d:/Users/zxshining/Pictures/python/.png', transparent=True, dpi=300, pad_inches = 0)
plt.show( )