当前位置: 首页 > 科技观察

matplotlib画双坐标轴设置和控制设置时间格式

时间:2023-03-18 18:46:15 科技观察

双y轴坐标轴图今天用matplotlib画图,想完成一个双坐标格式的图。fig=plt.figure(figsize=(20,15))ax1=fig.add_subplot(111)ax1.plot(demo0719['TPS'],'b-',label='TPS',linewidth=2)ax2=ax1.twinx()#这是双坐标的关键步骤ax2.plot(demo0719['successRate']*100,'r-',label='successRate',linewidth=2)横坐标设置时间间隔importmatplotlib.datesasmdateax1.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d%H:%M:%S'))#设置时间标签显示格式plt.xticks(pd.date_range(demo0719.index[0],demo0719.index[-1],freq='1min'))纵坐标设置显示百分比importmatplotlib.tickerasmtickfmt='%.2f%%'yticks=mtick.FormatStrFormatter(fmt)ax2.yaxis.set_major_formatter(yticks)matplotlib中的知识点,整个图像是一个Figure对象。Figure对象中可以包含一个或多个Axes对象。每个Axes对象都是一个具有自己坐标系的绘图区域。逻辑关系如下:一个Figure对应一张图片。标题就是标题。Axis为坐标轴,Label为坐标轴标签。Tick是刻度标记,TickLabel是刻度注释。标题就是标题。Axis为坐标轴,Label为坐标轴标签。Tick是刻度标记,TickLabel是刻度注释。add_subplot()官网matplotlib.pyplot.figurepyplot.figure()返回一个Figure对象,也就是一张图片。add_subplot(args,*kwargs)将返回Axes实例。twinx()matplotlib.axes.Axes方法2ax=twinx()创建一个Axes双胞胎,用于生成具有sharexx轴但独立y轴的图。self的y轴将在左侧有刻度,返回的轴将在右侧有刻度。意思是,创建一个单独的Y轴并共享X轴。双轴!类似于twiny()ax1.xaxis.set_major_formatterset_major_formatter(formatter)设置主要代码的格式化程序ACCEPTS:AFormatterinstanceDateFormatter()classmatplotlib.dates.DateFormatter(fmt,tz=None)这是一个类,创建了一个实例时间格式。strftime方法(传入格式字符串)。strftime(dt,fmt=None)请参阅datetime.strftime.fmtisastrftime()的文档formatstring.FormatStrFormatter()classmatplotlib.ticker.FormatStrFormatter(fmt)使用新样式的格式字符串(与str.format()所使用的一样)格式化刻度线。字段格式必须标记为x定义字符串格式。plt.xticksmatplotlib.pyplot.xticks(args,*kwargs)#returnlocs,labelswherelocsisanarrayofticklocationsand#labelsisanarrayofticklabels.locs,labels=xticks()#setthelocationsofthexticksxticks(arange(6))#setthelocationsandlabelsofthexticks('ange('Dick','Harry','Sally','Sue'))代码总结中文标签正常显示mpl.rcParams['axes.unicode_minus']=False#用来正常显示负号mpl.rc('xtick',labelsize=20)#设置轴刻度显示大小mpl.rc('ytick',labelsize=20)font_size=30#matplotlib.rcParams.update({'font.size':60})%matplotlibinlineplt.style.use('ggplot')data=pd.read_csv('simsendLogConvert_20160803094801.csv',index_col=0,encoding='gb2312',parse_dates=True)columns_len=len(data.columns)data_columns=data.columnsforxinrange(0,columns_len,2):print('列{}'.format(x))total=数据。ix[:,x]print('列{}'.format(x+1))successRate=(data.ix[:,x+1]/data.ix[:,x]).fillna(0)yLeftLabel=data_columns[x]yRightLable=data_columns[x+1]print('----------------开始绘制类型{}图----------------'.format(data_columns[x]))fig=plt.figure(figsize=(25,20))ax1=fig.add_subplot(111)#绘制总曲线ax1.plot(total,color='#4A7EBB',label=yLeftLabel,linewidth=4)#设置X轴坐标刻度线显示间隔ax1.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d%H:%M:%S'))#设置时间标签显示formatplt.xticks(pd.date_range(data.index[0],data.index[-1],freq='1min'))#时间间隔plt.xticks(rotation=90)#设置双轴,右Y轴ax2=ax1.twinx()#设置右边Y轴显示百分比fmt='%.2f%%'yticks=mtick.FormatStrFormatter(fmt)#绘制成功率图ax2.set_ylim(0,110)ax2.plot(successRate*100,color='#BE4B48',label=yRightLable,linewidth=4)ax2.yaxis.set_major_formatter(yticks)ax1.set_xlabel('时间',fontsize=font_size)ax1.set_ylabel(yLeftLabel,fontsize=font_size)ax2.set_ylabel(yRightLable,fontsize=font_size)legend1=ax1.legend(loc=(.02,.94),fontsize=16,shadow=True)legend2=ax2.legend(loc=(.02,.9),fontsize=16,shadow=True)legend1.get_frame().set_facecolor('#FFFFFF')legend2.get_frame().set_facecolor('#FFFFFF')plt.title(yLeftLabel+'&'+yRightLable,fontsize=font_size)plt.savefig('D:\\JGT\\Work-YL\\01布置任务\\04绘制图表和报告文件\\0803\\图片\\{}-{}'.format(yLeftLabel.replace(r'/',''),yRightLable.replace(r'/','')),dpi=300)参考Vami-drawing:matplotlibcoreanalysisSecondaryaxiswithtwinx():howtoaddtolegend?