matplotlib绘制折线图

代码

import matplotlib.pyplot as plt
import numpy as np

def get_data(txt_path: str = '', epoch: int = 100, target: str = '', target_data_len: int = 5):
# 函数介绍
# https://blog.csdn.net/LQ_001/article/details/130127681?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22130127681%22%2C%22source%22%3A%22LQ_001%22%7D
    num_list = []  # 将提取出来的数据保存到列表,并在最后返回
    data = open(txt_path, encoding="utf-8")  # 打开文件
    str1 = data.read()  # 将文件中读取到的内容转化为字符串
    data.close()  # 关闭文件
    for i in range(0, epoch):
        index = str1.find(target)  # 查找字符串str1中str2字符串的位置
        num_list.append(float(str1[index+len(target):index+len(target)+target_data_len]))  # 将需要的数据提取到列表中
        str1 = str1.replace(target, 'xxxx', 1)  # 替换掉已经查阅过的地方,' xxxx '表示替换后的内容,1表示在字符串中的替换次数为1

    return num_list


# 设置全局字体大小
plt.rcParams['font.size'] = 18

# 提取数据
list_ACC1  = get_data("./everything_to_Matlab/test.txt", 51, target="ACC1:", target_data_len=11)
list_ACC2  = get_data("./everything_to_Matlab/test.txt", 51, target="test2:", target_data_len=11)
list_loss1  = get_data("./everything_to_Matlab/test.txt", 50, target="loss1:", target_data_len=11)
list_loss2 = get_data("./everything_to_Matlab/test.txt", 50, target="loss2:", target_data_len=11)

fig, ax1 = plt.subplots()
# 绘制第一段折线
ax1.plot(list_ACC1, color = "#E18E6D", label = "lr_mul=1")
ax1.plot(list_ACC2, color = "#62B197", label = "lr_mul=0.5")
ax1.legend(loc='center right')

ax1.set_yticks([0.9995, 0.9943, 1.006])  # 设置Y轴刻度
ax1.set_yticklabels(["99.95%", "99.43%", "Accuracy"])
ax1.set_ylim(0.90, 1.006)  # 必须再 legend() 后面
ax1.set_xlim(0, 50)  # 必须再 legend() 后面
ax1.set_xlabel("epoch")
ax1.grid(axis='y')


# 绘制第二段折线
ax2 = ax1.twinx()
ax2.plot(list_loss1, color = "#E18E6D")
ax2.plot(list_loss2, color = "#62B197")
ax2.set_yticks([0.0005025579, 0.0001039364, 0.0079685581])  # 设置Y轴刻度
ax2.set_yticklabels(["0.5", "0.1", "loss(e-3)"])
ax2.set_ylim(0.0001039364 , 0.0079685581)  # 必须再 legend() 后面
ax2.set_xlim(0, 50)  # 必须再 legend() 后面
ax2.set_xlabel("epoch")
ax2.grid(axis='y')

plt.show()

结果

matplotlib绘制折线图_第1张图片

你可能感兴趣的:(ECG,matplotlib)