数据分析绘制随时间顺序变化图加入线性趋势线——numpy库的polyfit计算一次多项式拟合
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 导入数据
data = pd.read_csv(r'C:\Users\11712\notebooktrain1.csv')
# 假设数据包含 'date_time' 和 'speed' 列
data['date_time'] = pd.to_datetime(data['date_time']) # 确保时间列是 datetime 类型
data.set_index('date_time', inplace=True) # 将时间列设置为索引
# 筛选出2023年06月01日到2024年06月30日的数据
start_date = '2023-06-01 00:00:00'
end_date = '2023-06-15 23:45:00'
filtered_data = data[(data.index >= start_date) & (data.index <= end_date)]
# 绘制时间与速度的关系图
plt.figure(figsize=(15, 6)) # 设置图形大小
plt.plot(filtered_data.index, filtered_data['obs'], label='Speed', color='blue') # 绘制折线图
# 添加趋势线
# 将时间索引转换为数字序列(用于计算趋势线)
time_index = np.arange(len(filtered_data.index))
# 使用numpy的polyfit计算一次多项式拟合(即线性趋势线)
coefficients = np.polyfit(time_index, filtered_data['obs'], deg=1) # deg=1表示线性拟合
polynomial = np.poly1d(coefficients) # 创建多项式对象
trend_line = polynomial(time_index) # 计算趋势线的值
# 绘制趋势线
plt.plot(filtered_data.index, trend_line, label='Trend Line', color='red', linestyle='--')
# 添加标题和标签
plt.title('Speed from 2023-06-01 to 2023-06-15', fontsize=14)
plt.xlabel('Date', fontsize=12)
plt.ylabel('Speed', fontsize=12)
# 添加图例
plt.legend(fontsize=10)
# 格式化x轴的时间标签
plt.gcf().autofmt_xdate() # 自动旋转日期标签,避免重叠
plt.xticks(rotation=45) # 旋转x轴标签,便于阅读
# 显示图形
plt.tight_layout() # 调整布局
plt.show()
线的粗细、颜色修改
linewidth=3 参数,将趋势线的宽度设置为 3。你可以根据需要调整这个值,使其更粗或更细。
color='blue' 改为 color='yellow'。运行这段代码后,折线图将以黄色显示,而趋势线仍然保持为红色