Matplotlib绘图双纵坐标轴设置及控制设置时间格式
admin
2023-07-31 00:46:28
0

双y轴坐标轴图

今天利用matplotlib绘图,想要完成一个双坐标格式的图。

12345 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)

横坐标设置时间间隔

123 import matplotlib.dates as mdateax1.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\’))

纵坐标设置显示百分比

1234 import matplotlib.ticker as mtickfmt=\’%.2f%%\’yticks = mtick.FormatStrFormatter(fmt)ax2.yaxis.set_major_formatter(yticks)

知识点

在matplotlib中,整个图像为一个Figure对象。在Figure对象中可以包含一个,或者多个Axes对象。每个Axes对象都是一个拥有自己坐标系统的绘图区域。其逻辑关系如下:

一个Figure对应一张图片。

Title为标题。Axis为坐标轴,Label为坐标轴标注。Tick为刻度线,Tick Label为刻度注释。1

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

1 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方法(传入格式化字符串)。

123 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)

123456789 # 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 xticksxticks( arange(6) ) # set the locations and labels of the xticksxticks( arange(5), (\’Tom\’, \’Dick\’, \’Harry\’, \’Sally\’, \’Sue\’) )

代码汇总

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 #coding:utf-8import matplotlib.pyplot as plt import matplotlib as mplimport matplotlib.dates as mdateimport matplotlib.ticker as mtickimport numpy as npimport pandas as pdimport 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\’/\’,\’ \’)),

相关内容

热门资讯

Mobi、epub格式电子书如... 在wps里全局设置里有一个文件关联,打开,勾选电子书文件选项就可以了。
500 行 Python 代码... 语法分析器描述了一个句子的语法结构,用来帮助其他的应用进行推理。自然语言引入了很多意外的歧义,以我们...
定时清理删除C:\Progra... C:\Program Files (x86)下面很多scoped_dir开头的文件夹 写个批处理 定...
scoped_dir32_70... 一台虚拟机C盘总是莫名奇妙的空间用完,导致很多软件没法再运行。经过仔细检查发现是C:\Program...
65536是2的几次方 计算2... 65536是2的16次方:65536=2⁶ 65536是256的2次方:65536=256 6553...
小程序支付时提示:appid和... [Q]小程序支付时提示:appid和mch_id不匹配 [A]小程序和微信支付没有进行关联,访问“小...
pycparser 是一个用... `pycparser` 是一个用 Python 编写的 C 语言解析器。它可以用来解析 C 代码并构...
微信小程序使用slider实现... 众所周知哈,微信小程序里面的音频播放是没有进度条的,但最近有个项目呢,客户要求音频要有进度条控制,所...
Apache Doris 2.... 亲爱的社区小伙伴们,我们很高兴地向大家宣布,Apache Doris 2.0.0 版本已于...
python清除字符串里非数字... 本文实例讲述了python清除字符串里非数字字符的方法。分享给大家供大家参考。具体如下: impor...