# -*- coding:utf-8 -*-
import os
import time
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d
cur_dir = os.getcwd()
# 保存找到的文件
file_list = []
# 尝试不同的编码打开文件
encodings = ['utf-8', 'gbk']
def find_file_list(file_dir, temp):
"""
:param file_dir: 文件夹路径
:return: file_list: 文件列表
"""
for root, dirs, files in os.walk(file_dir):
for file in files:
if file.endswith(temp):
file_list.append(os.path.join(root, file))
if len(file_list) == 0:
print("can not find file")
exit()
return file_list
def create_line_chart(file_list, density):
"""
:param file_list: 文件列表
:param density: 折线图密度
:return:
"""
# 遍历文件列表,分别绘制折线图
for file in file_list:
# 折线图名称
save_pic_name = os.path.join(os.path.dirname(file), os.path.splitext(os.path.basename(file))[0] + ".png")
if os.path.exists(save_pic_name):
os.remove(save_pic_name)
# 处理数据,生成x轴和y轴,x轴为序号,y轴为数据
x = []
y = []
for encoding in encodings:
try:
with open(file, "r+", encoding=encoding) as f:
lines = f.readlines()
# 删除空行
lines = [line.strip() for line in lines if line.strip()]
for index, line in enumerate(lines):
x.append(index)
y.append(int(line))
break
except UnicodeDecodeError:
continue
# 创建一个图形窗口
plt.figure(figsize=(30, 6))
# 插值处理
if density > 0:
f = interp1d(x, y, kind='cubic')
x_new = np.linspace(min(x), max(x), density)
y_smooth = f(x_new)
else:
x_new = x
y_smooth = y
# 计算平均值
avg = np.mean(y)
# 绘制图
plt.scatter(x, y, color='gray', marker='o', s=5, alpha=0.5, label=os.path.splitext(os.path.basename(file))[0])
plt.plot(x_new, y_smooth, linestyle='--', color='red', label=os.path.splitext(os.path.basename(file))[0])
# 添加平均值线并设置为橙色
plt.axhline(avg, color='blue', label='avg')
# 添加图例
plt.legend()
# 设置横轴和纵轴标签
plt.xlabel('Time')
plt.ylabel('Value')
# 添加标签和标题
plt.title(os.path.splitext(os.path.basename(file))[0])
# # 显示图形
# plt.show()
# 保存为图片
plt.savefig(save_pic_name)
if __name__ == "__main__":
# 定义文件所在的绝对路径,默认是当前文件夹路径
file_dir = cur_dir
# 定义折线图平滑度,数值越小越平滑,如果density=0,则是真实数据折线图
density = 0
# 需要解析的文件后缀
temp = ".log"
find_file_list(file_dir, temp)
create_line_chart(file_list, density)
Python--绘制折线图,散列点,平均线
猜你喜欢
转载自blog.csdn.net/xch622114/article/details/133747766
今日推荐
周排行