Matplotlib绘图双纵坐标轴设置及控制设置时间格式
双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)横坐标设置时间间隔
import matplotlib.dates as mdate ax1.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))纵坐标设置显示百分比
import matplotlib.ticker as mtick fmt=%.2f%% yticks = mtick.FormatStrFormatter(fmt) ax2.yaxis.set_major_formatter(yticks)知识点
在matplotlib中,整个图像为一个Figure对象。控制在Figure对象中可以包含一个,格式或者多个Axes对象。绘图每个Axes对象都是双纵设置时间一个拥有自己坐标系统的绘图区域。其逻辑关系如下:

一个Figure对应一张图片。坐标轴设置及
Title为标题。控制Axis为坐标轴,格式Label为坐标轴标注。b2b供应网绘图Tick为刻度线,双纵设置时间Tick Label为刻度注释。坐标轴设置及

Title为标题。控制Axis为坐标轴,格式Label为坐标轴标注。Tick为刻度线,Tick Label为刻度注释。

add_subplot()
官网matplotlib.pyplot.figure
pyplot.figure()是返回一个Figure对象的,也就是一张图片。 add_subplot(args, *kwargs)The Axes instance will be returned.
twinx()
matplotlib.axes.Axes method2 ax = twinx()create a twin of Axes for generating a plot with a sharex x-axis but independent y axis. The y-axis of self will have ticks on left and the returned axes will have ticks on the right.
意思就是,服务器托管创建了一个独立的Y轴,共享了X轴。双坐标轴!
类似的还有twiny()
ax1.xaxis.set_major_formatter
set_major_formatter(formatter)Set the formatter of the major ticker
ACCEPTS: A Formatter instance
DateFormatter()
class matplotlib.dates.DateFormatter(fmt, tz=None)
这是一个类,创建一个时间格式的实例。strftime方法(传入格式化字符串)。
strftime(dt, fmt=None) Refer to documentation for datetime.strftime. fmt is a strftime() format string.FormatStrFormatter()
class matplotlib.ticker.FormatStrFormatter(fmt)Use a new-style format string (as used by str.format()) to format the tick. The field formatting must be labeled x
定义字符串格式。
plt.xticks
matplotlib.pyplot.xticks(args, *kwargs) # return locs, labels where locs is an array of tick locations and # labels is an array of tick labels. locs, labels = xticks() # set the locations of the xticks xticks( arange(6) ) # set the locations and labels of the xticks xticks( arange(5), (Tom, Dick, Harry, Sally, Sue) )代码汇总
#coding:utf-8 import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.dates as mdate import matplotlib.ticker as mtick import numpy as np import pandas as pd import os mpl.rcParams[font.sans-serif]=[SimHei] #用来正常显示中文标签 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}) %matplotlib inline plt.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.columns for x in range(0,columns_len,2): print(第{}列.format(x)) total=data.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) #绘制Total曲线图 ax1.plot(total,color=#4A7EBB,label=yLeftLabel,linewidth=4) # 设置X轴的坐标刻度线显示间隔 ax1.xaxis.set_major_formatter(mdate.DateFormatter(%Y-%m-%d %H:%M:%S))#设置时间标签显示格式 plt.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(Time,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-绘图: matplotlib核心剖析 Secondary axis with twinx(): how to add to legend? 免费信息发布网相关文章
联想电脑新机使用教程(带你一步步了解联想电脑新机,让你成为电脑操作达人!)
摘要:随着科技的不断进步,联想推出了一款全新的电脑,为用户带来更快、更强大的性能和更好的使用体验。然而,对于一些新手用户来说,上手新机可能会遇到一些困惑和难题。本教程将带领大家逐步了解联...2025-11-03
简介在日常开发中,我们的大部分时间都会花在阅读traceback模块信息以及调试代码上。本文我们将改进traceback模块,让其中的提示信息更加简洁准确。基于这一目的,我们将会自定义Exceptio2025-11-03
译者 |陈峻审校 |孙淑娟实现自助式用户协助往往是客户支持团队持续追求的目标之一。它不但能够有效地减少用户需求单量,而且可以让用户快速地找到所需的答案。数年前,美国运通美国运通)的一项研究就曾发现,有2025-11-03
“遇事不决,量子力学。”曾几何时,量子力学成为了人们口中的“玄学”。而利用量子力学原理进行有效计算的量子计算,正在引领新一轮科技发展的浪潮。“万物都是由量子构成的,我们天天生活在量子的世界,但是又感受2025-11-03OPPOR9s最新版本(OPPOR9s新版本发布,全新突破创新体验)
摘要:随着科技的不断进步,智能手机已经成为我们日常生活中不可或缺的一部分。OPPOR9s作为OPPO旗下最新一代旗舰机型,备受期待。本文将从外观设计、摄影功能、性能表现等多个方面,详细介...2025-11-03
一、误关闭CMD程序导致脚本未保存直接退出Jmeter客户端场景说明: 当我们使用jmeter.bat方式启动jmeter程序时,WIN会启动CMD程序打开一个面板如下图所示,当我们不小心关闭后,会导2025-11-03

最新评论