今日分享
阅读本文大概约8分钟
基于时间序列数据绘制标准化特征曲线,分享两种方法:seaborn模块的lineplot方法和matplotlib模块的plot的方法。seaborn里的lineplot函数所传数据必须为pandas的DataFrame数据结构,这与matplotlib里有较大区别,seaborn作图还是比较好看的,如果想自定义作图,建议使用原生的plt模块plot方法。注意:matplotlib和seaborn可混用。
import pandas as pd
import numpy as np
df=pd.read_excel(r".\test\data.xlsx",sheet_name="时间序列逐时数据")
df=df.sort_values(by="时间", ascending=True)
df=df.replace("",np.NaN)
df["时间"]=pd.date_range(start="2019/1/1",periods=8760,freq="h")
df.head()
#全部列数
C=len(df.columns[1:])
# # #数据记录长度
L=len(df.时间)
#删除含有空值的列
df_1=df.dropna(axis=1, how='all', thresh=L*0.70, subset=None, inplace=False)
display(df_1)
#删除空值列剩余的列数
C1=len(df_1.columns[1:])
print("删除缺失值列前后对比:",(C,C1))
#待分析逐时特征值
df_2=df_1.set_index("时间").T
df_2.index=list(map(lambda x: x[8:],list(df_1.columns[1:])))#截取列中需要的字段
df_3=df_2.T.reset_index()
df_3["时间"]=df_3["时间"].apply(lambda x:x.hour)
df_3=df_3.groupby("时间",as_index=False).mean()
df_3
#去除特征值为0的列
df_4=df_3.copy().replace(0,np.NaN)
df_4["时间"]=df_3.时间.values
L_1=len(df_4.时间)
df_4=df_4.dropna(axis=1, how='all', thresh=L_1*0.80, subset=None, inplace=False)
df_5=df_4.replace(np.NaN,0)
df_5
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler
from sklearn import preprocessing
X = df_5.iloc[:,1:].values
min_max_scaler = preprocessing.MinMaxScaler()
X_minmax = min_max_scaler.fit_transform(X)
X1=pd.DataFrame(X_minmax)
X1.columns=df_5.columns[1:]
X1["时间"]=df_5.时间.values
X2=X1.set_index("时间")
display(X2)
方法一:利用sns模块的lineplot方法
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams["font.sans-serif"]=['SimHei',"Microsoft YaHei"]
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
#构建分类筛选需要分析的特征,这里在excel里面根据特征指定编号对应分类一下,便于后续分类筛选列。
fxzl=pd.read_excel(r".\test\分类编码.xlsx")
#分类1
fxzl_1=fxzl[fxzl.分类编号==291]["特征名称"].to_list()[:8]#此处限制显示8列,lineplot方法marks好像不能超过8个,不然会报错。
#分类2
fxzl_2=fxzl[fxzl.分类编号==295]["特征名称"].to_list()
#分类3
fxzl_3=fxzl[fxzl.分类编号==315]["特征名称"].to_list()
#分类4
fxzl_4=fxzl[fxzl.分类编号==329]["特征名称"].to_list()
fxzl_list=[fxzl_1,fxzl_2,fxzl_3,fxzl_4]
fxmc_list=["分类1","分类2"," 分类3","分类4"]
for i in range(4):
X3=X2[fxzl_list[i]]
L_3=len(X3.columns)
zl=list(X3.columns)
plt.figure(figsize=(10,6), dpi= 80)
%config InlineBackend.figure_format='svg'
sns.lineplot(data=X3,markers=True, dashes=False)
plt.xticks(X2.index, fontsize=10, horizontalalignment='center')
plt.yticks(fontproperties = 'Times New Roman',size = 12)
plt.xticks(fontproperties = 'Times New Roman',size = 12)
plt.xlabel("时间(h)",fontsize=14)
plt.ylim(0,1,0.1)
plt.legend(loc='upper left',edgecolor='none',facecolor='none')
plt.title("{}".format(fxmc_list[i]),loc="center")
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.show()
方法二:直接利用plt.plot()方法
markers=["o",".","<","p","+","D",">","*","x","H","_","s","d","v",]
colors= ['b','g','r','c','m','y','violet', 'wheat','whitesmoke',"yellowgreen",]
for k in range(4):
X3=X2[fxzl_list[k]]
zl=list(X3.columns)
%config InlineBackend.figure_format='svg'
fig =plt.figure(figsize=(10,6), dpi=80)
for i in range(len(zl)):
plt.plot(X2.index,X2[["{}".format(zl[i])]],
marker=markers[i], markerfacecolor=colors[i], markersize=5,markeredgewidth=0.5,
color=colors[i], linewidth=0.5, linestyle="-",label=zl[i]
)
np.set_printoptions(precision=2)
# # 设置横轴记号
plt.xticks(np.linspace(0,23,24,endpoint=True,dtype=int),fontproperties = 'Times New Roman',fontsize=12)
# # 设置纵轴的上下限
plt.yticks(fontproperties = 'Times New Roman',fontsize=12)
plt.xlabel('时间', fontdict={'color': 'black',
'family': "Microsoft YaHei",
'weight': 'normal',
'size': 14})
plt.ylabel('', fontdict={'color': 'black',
'fontstyle': 'normal',
'family': ['Times New Roman'],
'weight': 'normal',
'size': 14})
plt.xlim(-1,24,23)
plt.ylim(0,1,0.1)
plt.legend(loc='upper left',edgecolor='none',facecolor='none')
plt.title("{}".format(fxmc_list[k]),loc="center")
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.show()
方法详细说明
1、seaborn.lineplot方法
seaborn.lineplot(x=None, y=None, hue=None,
size=None, style=None, data=None,
palette=None, hue_order=None, hue_norm=None,
sizes=None, size_order=None, size_norm=None,
dashes=True, markers=None, style_order=None,
units=None, estimator='mean', ci=95, n_boot=1000,
sort=True, err_style='band', err_kws=None,
legend='brief', ax=None, **kwargs)
参数说明:
data:是DataFrame类型的;
#以下均为可选项:
x,y:数据中变量的名称;
hue:数据中变量名称(比如:二维数据中的列名),对将要生成不同颜色的线进行分组,可以是分类或数据。
size:数据中变量名称(比如:二维数据中的列名),对将要生成不同宽度的线进行分组,可以是分类或数据。
style:数据中变量名称(比如:二维数据中的列名),对将生成具有不同破折号、或其他标记的变量进行分组。
palette:调试板名称,列表或字典类型,设置hue指定的变量的不同级别颜色。
hue_order:列表(list)类型,指定hue变量出现的指定顺序,否则他们是根据数据确定的。
hue_norm:tuple或Normalize对象
sizes:list dict或tuple类型,设置线宽度,当其为数字时,它也可以是一个元组,指定要使用的最大和最小值,会自动在该范围内对其他值进行规范化。
units:对变量识别抽样单位进行分组,使用时,将为每个单元绘制一个单独的行。
estimator:pandas方法的名称或回调函数或者None,用于在同一x水平上聚合y变量的多个观察值的方法,如果为None,则将绘制所有观察结果。
2、matplotlib.plot方法
具体参见官方文档https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot)
3、可选颜色参数库
#