学习编程后,我突然意识到用python画画是一件很容易的事。 想放松的伙伴,今天一起画时间序列图吧。
一.数据读取和处理
在pandas中读取CSV文件时,keep_default_na参数将空数据更改为空字符串
从原始数据信息来看,原始数据分为3天,时间粒度为3min
使用pandas date_range函数生成时间序列时间数据,并指定freq='180s'importpandasaspd
importmatplotlib.pyplotasplt
importmatplotlib.datesasmdates
%matplotlibinline
PLT.rcparams [ ' font.sans-serif ' ]=[ ' simhei ' ] #显示中文(windows )
PLT.rcparams [ ' axes.unicode _ MINUS ' ]=false #用于成功显示负号
无df=PD.read _ CSV (traffic _ analysis _ macro.CSV (,keep_default_na=False )数据被视为空字符串
#df.drop(['region_id'],axis=1,inplace=True ) )。
#显示原始数据集的状况
print(shape: )、df.shape )。
print('describle: ',df.describe ) )
打印(数据头: )、df.head ) )
#该数据集分为三天,时间粒度为3min;
#首先按日划分数据
df_0912=df[:480]
df_0915=df[480:960]
df_0916=df[960:]
#生成时间序列: x轴比例数据
table=PD.data frame ([ iforiinrange (480 ),columns=['value'],index=PD.date _ range (' 00:0336000 )
二.绘图图形#图像尺寸设定
fig=PLT.figure (fig size=(15,9 ),dpi=100 ) ) ) ) ) ) )。
ax=fig.add_subplot(111 ) )
#X轴时标格式刻度显示
ax.xaxis.set _ major _ formatter (mdates.date formatter (' % h : % m ' ) )
PLT.xticks(PD.date_range ) table.index[-1],table.index[-1],freq='H ' ),rotation=45 ) ) )。
#绘图
ax.plot(table.index,df_0912('AVG_speed '),color='r ',label='9月12日' ) ) ) ) ) )
ax.plot(table.index,df_0915['avg_speed'],color='y ',label='9月15日')
ax.plot(table.index,df_0916['avg_speed'],color='g ',label='9月16日') ) ) ) ) ) )。
#辅助线
sup_line=[35foriinrange(480] )
ax.plot(table.index,sup_line,color='black ',linestyle='--',linewidth='1',label='辅助线)
PLT.xlabel('time_point ',fontsize=14 ) #X轴标签
PLT.ylabel(speed )、fontsize=16 ) #Y轴标签
ax.legend(#图例
plt.title (“车速时序图”、fontsize=25、color='black”、pad=20 ) )。
PLT.GCF(.autofmt_xdate ) )。
#隐藏-上右侧线条
# ax.spines [ ' right ' ].set _ color (' none ' )
# ax.spines [ ' top ' ].set _ color (' none ' )
#PLT.savefig(speed.png ) )。
plt.show () )
三、效果图如下
以上就是在python上用matlibplot绘制时间序列图的方法。 更多Python学习推荐:JQ教程网Python大全。
您感兴趣的文章: