Matplotlib处理常见中文的一些情形
所在领域经常涉及到处理一些时序图,需要在以合适的方式在x axis上显示中文时间。
这个问题虽然很小,但是因为专业的原因,需要经常在x轴上展示多种多样的时间,比如只展示月-日-时,这种非常规的x轴label, 同时要求该部分占图片比例不能太大,不然影响美观。而网络上关于x轴时间的处理相对较少,算写个地方记录下。
这是一篇记录matplotlib处理的博客,同时怀念和某只增某只斌的共渡三年的硕士生涯, 最后非常感谢某增精彩的工作和日常的骚扰为这篇博客提供了素材(大概又要被说矫情了哈哈哈哈 以下是干货)。
关键点
- 导入可以显示中文的参数
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
-
x坐标轴通过设置格式以及旋转 以显示美观(没强迫症的您随意)
ax1.xaxis.set_major_formatter(mdate.DateFormatter('%H:%M')) plt.xticks(rotation=30)
输入数据、代码及结果
- 输入数据只有一部分,太长影响美观,读者需要脑补 哈哈哈
4:15,7,1,1 4:30,53,21,46 4:45,673,433,588 5:00,2449,1711,2209 5:15,5555,4522,5094 5:30,8854,8710,9431 5:45,12886,14687,13918 6:00,16459,23762,20121 6:15,20542,37169,26034 6:30,24708,59783,34398 6:45,28093,88462,43049 7:00,30505,134718,51161 7:15,32046,180216,59468 7:30,35503,215490,64192 7:45,39600,239502,70168 8:00,43334,228761,73596 8:15,45938,202122,72283 8:30,45756,167016,68193 8:45,46982,138231,64956
-
代码
import pandas as pd import numpy as np from datetime import datetime import matplotlib.dates as mdate import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus']=False #用来正常显示负号 def convert(strAim): t = strAim.split(":") h, m, s = int(t[0]),float(t[1])/60.0,float(t[2])/3600.0 return h+m+s def draw(addressIn,addressOut): df =pd.read_csv(addressIn,header = None) #print(df.head()) x = [] y1 = [] y2 = [] y3 = [] for i in range(len(df)): tx = datetime.strptime('2017-8-1 '+df.iloc[i][0], '%Y-%m-%d %H:%M') x.append(tx) y1.append(df.iloc[i][1]) y2.append(df.iloc[i][2]) y3.append(df.iloc[i][3]) fig1 = plt.figure(figsize=(12,6))#figsize=(16,8) ax1 = fig1.add_subplot(1,1,1) ax1.plot(x,y1,color='green',label='假期')#折线图 ax1.plot(x,y2,color='black',label='工作日') ax1.plot(x,y3,color='red',ls='--',label='非工作日') ax1.xaxis.set_major_formatter(mdate.DateFormatter('%H:%M')) #plt.xticks(pd.timedelta_range(start='05:00:00.000000', periods=38, freq='30T'),rotation=90) #plt.xticks(x) plt.xticks(rotation=30) #plt.ylim(0,6000000) #ax1.set_title('全天') ax1.set_xlabel('时间') ax1.set_ylabel('日客流量(人次)') plt.legend(loc='upper right') plt.subplots_adjust(left=0.2, bottom=0.2, right=0.8, top=0.8) plt.savefig('pic%s.png'%(addressOut),dpi=100) if __name__ == '__main__': draw('differDay.csv','differDay')
-
结果图示