双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为坐标轴标注。Tick为刻度线,Tick Label为刻度注释。

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

add_subplot()

The Axes instance will be returned.

twinx()

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 the formatter of the major ticker
ACCEPTS: A Formatter instance

DateFormatter()

strftime方法(传入格式化字符串)。

strftime(dt, fmt=None)
Refer to documentation for datetime.strftime.
fmt is a strftime() format string.

FormatStrFormatter()

Use a new-style format string (as used by str.format()) to format the tick. The field formatting must be labeled x
定义字符串格式。

plt.xticks

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

参考


  1. Vami-绘图: matplotlib核心剖析
  2. Secondary axis with twinx(): how to add to legend?

Matplotlib绘图双纵坐标轴设置及控制设置时间格式的更多相关文章

  1. element-ui 时间设置 获取固定的时间格式

    <el-date-picker v-model="time1" type="daterange" start-placeholder="开始日期 ...

  2. WordPress 博客文章时间格式the_time()设置

    国外设计的WordPress 主题里的文章的时间格式是类似“十一月 21, 2010”这种格式的,而中国人习惯的是年在前,月紧跟其后,日在末尾,所以看国外的就显得很别扭,但是我们可以通过修改WP时间代 ...

  3. matplotlib绘图教程,设置标签与图例

    大家好,欢迎大家阅读周四数据处理专题,我们继续介绍matplotlib作图工具. 在上一篇文章当中我们介绍了matplotlib这个包当中颜色.标记和线条这三种画图的设置,今天我们同样也介绍三种新的设 ...

  4. Python matplotlib绘图设置图例

    一.语法简介 plt.legend(loc=2,edgecolor='red',facecolor='green',shadow='True',fontsize=10) #edgecolor 图例边框 ...

  5. SAP、BW 权限控制设置

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  6. matplotlib交互模式与pacharm单独Figure设置

    matplotlib交互模式与pacharm单独Figure设置 觉得有用的话,欢迎一起讨论相互学习~Follow Me Matpotlib交互模式 在运行python程序时有时候需要生成以下的 动态 ...

  7. 使用matplotlib绘制常用图表(2)-常用图标设置

    一.使用subplots绘制子图 import numpy as np from matplotlib import pyplot as plt %matplotlib inline x = np.a ...

  8. matplotlib 绘图

    http://blog.csdn.net/jkhere/article/details/9324823 都打一遍 5 matplotlib-绘制精美的图表 matplotlib 是python最著名的 ...

  9. python之matplotlib绘图基础

    Python之matplotlib基础 matplotlib是Python优秀的数据可视化第三方库 matplotlib库的效果可参考 http://matplotlib.org/gallery.ht ...

随机推荐

  1. Codeforces.997C.Sky Full of Stars(容斥 计数)

    题目链接 那场完整的Div2(Div1 ABC)在这儿.. \(Description\) 给定\(n(n\leq 10^6)\),用三种颜色染有\(n\times n\)个格子的矩形,求至少有一行或 ...

  2. bzoj 4036 集合幂级数

    集合幂级数其实就是一种集合到数的映射,并且我们针对集合的一些操作(or  xor and specil or )为这种映射定义运算.其中一些东西可以通过某些手段将其复杂度降低. orz vfk /** ...

  3. 【BZOJ-4212】神牛的养成计划 Trie树 + 可持久化Trie树

    4212: 神牛的养成计划 Time Limit: 10 Sec  Memory Limit: 512 MBSubmit: 136  Solved: 27[Submit][Status][Discus ...

  4. HDU 5839 Special Tetrahedron 计算几何

    Special Tetrahedron 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5839 Description Given n points ...

  5. hdu 5735 Born Slippy 暴力

    Born Slippy 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5735 Description Professor Zhang has a r ...

  6. CentOS下KVM网卡设置成网桥时获取镜像端口的流量

    首先,网桥配置好之后就能实现一个简单的交换机,而交换机的特点就是MAC地址学习,那么KVM的网卡设置成网桥之后,也就是相当于连接到了交换机上. 此时如果要实现在二层交换机或三层交换机做端口镜像,并把这 ...

  7. spring-boot 速成(10) -【个人邮箱/企业邮箱】发送邮件

    发邮件是一个很常见的功能,代码本身并不复杂,有坑的地方主要在于各家邮件厂家的设置,下面以qq个人邮箱以及腾讯企业邮箱为例,讲解如何用spring-boot发送邮件: 一.添加依赖项 compile ' ...

  8. oracle直接读写ms sqlserver数据库(二)配置透明网关

    环境说明: 数据库版本:11gR2 透明网关版本:11g 操作系统Windows Server2008_64位 ORACLE_HOME目录:D:\app\Administrator\product\1 ...

  9. mycat应用场景

    mycat应用场景 以下是几个典型的应用场景:单纯的读写分离,此时配置最为简单,支持读写分离,主从切换分表分库,对于超过1000万的表进行分片,最大支持1000亿的单表分片多租户应用,每个应用一个库, ...

  10. log4j deadlock

    用了这么久的Log4j这次倒下了,而且官方也还没有给出解决方案. 描述:tomcat 经过一天多时间的访问,出现了hang ,使用 Jstack 查看堆栈后,发现现成 blocked ,主要是 Log ...