matplotlib绘图知识库:
1.绘图核心步骤:
- 导入库: import matplotlib.pyplot as plt
- 准备数据:x,y轴数据
- 画图:选择图形类型(折线图、散点图、柱状图)
- 美化:加标题、标签、图例、网格
- 显示:plt.show()
2.常用图形:
| 折线图 | plt.plot() | 数据随时间变化趋势 |
| 散点图 | plt.scatter() | 两个变量的分布关系 |
| 柱状图 | plt.bar() | 比较不同类别的数量大小 |
对于灰色预测模型,把折线图和散点图结合使用(折线表示趋势,散点表示数据点)
3.绘图函数:
| 绘图函数 | 用途 | 示例 |
| plt.title() | 加标题 | plt.title('灰色预测模型') |
| plt.xlabel() | 加x轴标签 | plt.xlabel('年份') |
| plt.ylabel() | 加y轴标签 | plt.ylabel('降雨量') |
| plt.legend() | 显示图例(配合label参数) | plt.legend() |
| plt.grid(True) | 显示网格 | plt.grid(True) |
| plt.figure(figsize=(宽,高)) | 画布大小 | plt.figure(figsize=(10,5)) |
4.举个例子:
plt.plot(x,y1,'o--',color='red',label='原始数据') #绘制的图像由虚线和圆点构成,红色,标签是原始数据
plt.plot(x,y2,'s-',color='blue',label='预测数据') #绘制的图像由实线和方块组成,蓝色,标签是预测数据
plt.scatter(x,y,color='red',marker='s',s=50) #绘制的图像是红色的方块状散点图,散点大小是50
案例分析:以灰色预测模型的拟合效果图为例
导入相关库并设置显示参数:
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore') #忽略运行时警告信息
plt.rcParams['axes.unicode_minus'] = False #修复负号显示
plt.rcParams['font.sans-serif'] = ['SimHei']
数据处理:
x_data = [i+1 for i in range(len(lst))]
x_data2 = [i+6 for i in range(len(pre_val) - 5)]
y_data = lst
y_data2 = pre_val[5:]
其中,y_data是原始数据,y_data2是预测序列的后5个预测数据.
绘制散点折线图:
plt.plot(x_data,y_data,'o-',color = 'blue',label = '原始数据',markersize = 8)
plt.plot(x_data2,y_data2,'s--',color = 'red',label = '预测数据',markersize = 8)
绘制参考线:
考虑到可视化图像的可读性,模拟一条预测序列的虚线,让图形更易懂。
#参考线
x = [i+1 for i in range(10)]
y = pre_val
plt.plot(x,y,'--',color = 'green',label = '拟合值',markersize = 6)
设置图片参数:
plt.title('灰色预测模型')
plt.xlabel('年份')
plt.ylabel('降雨量')
plt.legend()
plt.grid(True)
plt.show()
图形展示:
灰色预测模型完整代码:
#灰色预测模型核心部分 import numpy as np import pandas as pd lst = [600,620,650,680,700] n = len(lst) #级比检验 def init_check(data): lst1 = [] for i in range(1,len(data)): a = data[i-1] / data[i] if a >= np.e**(-2/(n+1)) and a <= np.e**(2/(n+1)): lst1.append(a) else: print(f"级比{a}不在检验区间内,数据不适合直接建模") return lst1 answer = init_check(lst) #累加生成 x1 = [] for i in range(len(lst)): if i == 0: x1.append(lst[i]) else: x1.append(lst[i]+x1[i-1]) #均值生成 x2 = [] for i in range(len(x1)): if i == 0: continue else: x2.append((x1[i]+x1[i-1])/2) #求解参数 B = np.array([ [-x2[0],1], [-x2[1],1], [-x2[2],1], [-x2[3],1] ]) Y = np.array([620,650,680,700]).T result = np.linalg.inv(B.T @ B) @ B.T @ Y a = result[0] b = result[1] print("a =", a) print("b =", b) pre = [] #代入时间响应公式 for i in range(len(lst)): val = (lst[0] - b/a)*np.e**(-a*i) + b/a pre.append(val) print("累加预测序列:",pre) #累减还原 pre_val = [] for i in range(len(pre)): if i == 0: pre_val.append(pre[i]) else: val1 = pre[i] - pre[i-1] pre_val.append(val1) print("最终预测序列:",pre_val) #残差检验 def residual_check(pre_list,ini_list): residuals = [] sum = 0 for i in range(len(ini_list)): #相对残差 residual = abs(pre_list[i] - ini_list[i])/ ini_list[i] sum += residual residuals.append(residual) avg = sum / len(residuals) if avg < 0.05: print(f"残差检验{avg}优秀") elif avg < 0.10: print(f"残差检验{avg}合格") else: print("残差检验不通过") return residuals residuals = residual_check(pre_val,lst) #后验差检验 #绝对残差 abs_residuals = [lst[i] - pre_val[i] for i in range(n)] #原始数据的标准差s1 s1 = np.std(lst) s2 = np.std(abs_residuals) c = s2 / s1 if c < 0.35: print("好") elif c < 0.5: print("合格") else: print("不合格") #p值 def calcute_p(residual_list): count = 0 avg_res = np.mean(residual_list) # 残差的均值 s2 = np.std(residual_list) # 残差的标准差 lower = avg_res - 0.6745 * s1 # 区间下限 upper = avg_res + 0.6745 * s1 # 区间上限 for i in range(len(residual_list)): if lower <= residual_list[i] <= upper: # 判断是否落在区间内 count += 1 p = count / len(residual_list) if p > 0.95: print("一级") elif p > 0.80: print("二级") else: print("不合格") return p calcute_p(abs_residuals) #外推预测 pre = [] for i in range(len(lst)+5): val = (lst[0] - b/a)*np.e**(-a*i) + b/a pre.append(val) print("累加预测序列:",pre) #累减还原 pre_val = [] for i in range(len(pre)): if i == 0: pre_val.append(pre[i]) else: val1 = pre[i] - pre[i-1] pre_val.append(val1) print("最终预测序列:",pre_val) #绘制拟合效果图 import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') #忽略运行时警告信息 plt.rcParams['axes.unicode_minus'] = False #修复负号显示 plt.rcParams['font.sans-serif'] = ['SimHei'] x_data = [i+1 for i in range(len(lst))] x_data2 = [i+6 for i in range(len(pre_val) - 5)] y_data = lst y_data2 = pre_val[5:] plt.plot(x_data,y_data,'o-',color = 'blue',label = '原始数据',markersize = 8) plt.plot(x_data2,y_data2,'s--',color = 'red',label = '预测数据',markersize = 8) #参考线 x = [i+1 for i in range(10)] y = pre_val plt.plot(x,y,'--',color = 'green',label = '拟合值',markersize = 6) plt.title('灰色预测模型') plt.xlabel('年份') plt.ylabel('降雨量') plt.legend() plt.grid(True) plt.show()注:1.计算p值要用绝对残差。2.由于绘图代码简略,绘制的图片不够美观。可根据自身喜好调整参数