资讯专栏INFORMATION COLUMN

Matplotlib绘图双纵坐标轴设置及控制设置时间格式

xingpingz / 3493人阅读

摘要:双轴坐标轴图今天利用绘图,想要完成一个双坐标格式的图。这是双坐标关键一步横坐标设置时间间隔设置时间标签显示格式纵坐标设置显示百分比知识点在中,整个图像为一个对象。双坐标轴类似的还有这是一个类,创建一个时间格式的实例。

双y轴坐标轴图

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

</>复制代码

  1. fig=plt.figure(figsize=(20,15))
  2. ax1=fig.add_subplot(111)
  3. ax1.plot(demo0719["TPS"],"b-",label="TPS",linewidth=2)
  4. ax2=ax1.twinx()#这是双坐标关键一步
  5. ax2.plot(demo0719["successRate"]*100,"r-",label="successRate",linewidth=2)
横坐标设置时间间隔

</>复制代码

  1. import matplotlib.dates as mdate
  2. ax1.xaxis.set_major_formatter(mdate.DateFormatter("%Y-%m-%d %H:%M:%S"))#设置时间标签显示格式
  3. plt.xticks(pd.date_range(demo0719.index[0],demo0719.index[-1],freq="1min"))
纵坐标设置显示百分比

</>复制代码

  1. import matplotlib.ticker as mtick
  2. fmt="%.2f%%"
  3. yticks = mtick.FormatStrFormatter(fmt)
  4. 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)

</>复制代码

  1. The Axes instance will be returned.

twinx()

matplotlib.axes.Axes method2

</>复制代码

  1. ax = twinx()

</>复制代码

  1. 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)

</>复制代码

  1. Set the formatter of the major ticker
    ACCEPTS: A Formatter instance

DateFormatter()

class matplotlib.dates.DateFormatter(fmt, tz=None)
这是一个类,创建一个时间格式的实例。

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

</>复制代码

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

class matplotlib.ticker.FormatStrFormatter(fmt)

</>复制代码

  1. 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)

</>复制代码

  1. # return locs, labels where locs is an array of tick locations and
  2. # labels is an array of tick labels.
  3. locs, labels = xticks()
  4. # set the locations of the xticks
  5. xticks( arange(6) )
  6. # set the locations and labels of the xticks
  7. xticks( arange(5), ("Tom", "Dick", "Harry", "Sally", "Sue") )
代码汇总

</>复制代码

  1. #coding:utf-8
  2. import matplotlib.pyplot as plt
  3. import matplotlib as mpl
  4. import matplotlib.dates as mdate
  5. import matplotlib.ticker as mtick
  6. import numpy as np
  7. import pandas as pd
  8. import os
  9. mpl.rcParams["font.sans-serif"]=["SimHei"] #用来正常显示中文标签
  10. mpl.rcParams["axes.unicode_minus"]=False #用来正常显示负号
  11. mpl.rc("xtick", labelsize=20) #设置坐标轴刻度显示大小
  12. mpl.rc("ytick", labelsize=20)
  13. font_size=30
  14. #matplotlib.rcParams.update({"font.size": 60})
  15. %matplotlib inline
  16. plt.style.use("ggplot")
  17. data=pd.read_csv("simsendLogConvert_20160803094801.csv",index_col=0,encoding="gb2312",parse_dates=True)
  18. columns_len=len(data.columns)
  19. data_columns=data.columns
  20. for x in range(0,columns_len,2):
  21. print("第{}列".format(x))
  22. total=data.ix[:,x]
  23. print("第{}列".format(x+1))
  24. successRate=(data.ix[:,x+1]/data.ix[:,x]).fillna(0)
  25. yLeftLabel=data_columns[x]
  26. yRightLable=data_columns[x+1]
  27. print("------------------开始绘制类型{}曲线图------------------".format(data_columns[x]))
  28. fig=plt.figure(figsize=(25,20))
  29. ax1=fig.add_subplot(111)
  30. #绘制Total曲线图
  31. ax1.plot(total,color="#4A7EBB",label=yLeftLabel,linewidth=4)
  32. # 设置X轴的坐标刻度线显示间隔
  33. ax1.xaxis.set_major_formatter(mdate.DateFormatter("%Y-%m-%d %H:%M:%S"))#设置时间标签显示格式
  34. plt.xticks(pd.date_range(data.index[0],data.index[-1],freq="1min"))#时间间隔
  35. plt.xticks(rotation=90)
  36. #设置双坐标轴,右侧Y轴
  37. ax2=ax1.twinx()
  38. #设置右侧Y轴显示百分数
  39. fmt="%.2f%%"
  40. yticks = mtick.FormatStrFormatter(fmt)
  41. # 绘制成功率图像
  42. ax2.set_ylim(0,110)
  43. ax2.plot(successRate*100,color="#BE4B48",label=yRightLable,linewidth=4)
  44. ax2.yaxis.set_major_formatter(yticks)
  45. ax1.set_xlabel("Time",fontsize=font_size)
  46. ax1.set_ylabel(yLeftLabel,fontsize=font_size)
  47. ax2.set_ylabel(yRightLable,fontsize=font_size)
  48. legend1=ax1.legend(loc=(.02,.94),fontsize=16,shadow=True)
  49. legend2=ax2.legend(loc=(.02,.9),fontsize=16,shadow=True)
  50. legend1.get_frame().set_facecolor("#FFFFFF")
  51. legend2.get_frame().set_facecolor("#FFFFFF")
  52. plt.title(yLeftLabel+"&"+yRightLable,fontsize=font_size)
  53. plt.savefig("D:JGTWork-YL1布置的任务4绘制曲线图和报告文件803出图{}-{}".format(yLeftLabel.replace(r"/"," "),yRightLable.replace(r"/"," ")),dpi=300)

参考

Vami-绘图: matplotlib核心剖析 ↩

Secondary axis with twinx(): how to add to legend? ↩

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/38078.html

相关文章

  • Python--matplotlib绘图可视化知识点整理

    摘要:本文作为学习过程中对一些常用知识点的整理,方便查找。所有绘图操作仅对当前图和当前坐标有效。表示把图标分割成的网格。每个对象都是一个拥有自己坐标系统的绘图区域。避免比例压缩为椭圆数据可视化入门教程绘图核心剖析如何调整子图的大小 本文作为学习过程中对matplotlib一些常用知识点的整理,方便查找。 强烈推荐ipython无论你工作在什么项目上,IPython都是值得推荐的。利用ipyt...

    nifhlheimr 评论0 收藏0
  • 数据可视化Seaborn从零开始学习教程(三) 数据分布可视化篇

    摘要:数据集分布可视化当处理一个数据集的时候,我们经常会想要先看看特征变量是如何分布的。直方图在横坐标的数据值范围内均等分的形成一定数量的数据段,并在每个数据段内用矩形条显示轴观察数量的方式,完成了对的数据分布的可视化展示。 作者:xiaoyu微信公众号:Python数据科学知乎:python数据分析师 Seaborn学习大纲 seaborn的学习内容主要包含以下几个部分: 风格管理 ...

    Tamic 评论0 收藏0
  • 这里有8个流行的Python可视化工具包,你喜欢哪个?

    摘要:下面,作者介绍了八种在中实现的可视化工具包,其中有些包还能用在其它语言中。当提到这些可视化工具时,我想到三个词探索数据分析。还可以选择样式,它模拟了像和等很流行的美化工具。有很多数据可视化的包,但没法说哪个是最好的。 showImg(https://segmentfault.com/img/remote/1460000019029121); 作者:Aaron Frederick 喜欢用...

    testbird 评论0 收藏0
  • 8个流行的Python可视化工具包,你更钟意哪一个?

    摘要:最终证明,及其相关工具的效率很高,但就演示而言它们并不是最好的工具。我按编号用颜色编码了每个节点,代码如下用于可视化上面提到的稀疏图形的代码如下这个图形非常稀疏,通过最大化每个集群的间隔展现了这种稀疏化。 showImg(http://upload-images.jianshu.io/upload_images/13825820-3a550fd2e61e1674.jpg?imageMo...

    iliyaku 评论0 收藏0

发表评论

0条评论

xingpingz

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<