点击上方"蓝字"关注我们

Python大数据分析

记录   分享   成长

添加微信号"

CNFeffery

"加入技术交流群

最近有小伙伴私信我关于matplotlib时间类型刻度的设置问题,第一感觉就是官网有好多例子介绍啊

 转念一想,在实际应用中类似设置还挺多和好多小伙伴询问,那么本期就就简单介绍下Python-matplotlib「刻度(ticker)」 的使用方法,并结合具体例子讲解时间刻度设置问题,使小伙伴们定制化刻度不再烦恼。本期推文只要涉及知识点如下:

Tick locators 刻度位置介绍

Tick formatters 刻度形式介绍

时间刻度的设置

位置(Locator)和形式 (Formatter)

Tick Locator

Tick Locator主要设置刻度位置,这在我的绘图教程中主要是用来设置副刻度(minor),而Formatter则是主要设置刻度形式。Matplotlib对这两者则有着多种用法,其中Locator的子类主要如下:

定位器

解释说明

AutoLocator

自动定位器,多数绘图的默认刻度线定位。

MaxNLocator

在最合适的位置找到带有刻度的最大间隔数。

LinearLocator

从最小到最大之间的均匀刻度定位。

LogLocator

从最小到最大呈对数形式的刻度定位。

MultipleLocator

刻度和范围是基数的倍数;整数或浮点数。(自定义刻度用较多的方法)。

FixedLocator

固定刻度定位。刻度位置是固定的。

IndexLocator

索引定位器。

NullLocator

空定位器。无刻度位置。

SymmetricalLogLocator

与符号规范一起使用的定位器;对于超出阈值的部分,其工作原理类似于LogLocator,如果在限制范围内,则将其加0。

LogitLocator

用于logit缩放的刻度定位器。

OldAutoLocator

选择一个MultipleLocator并动态重新分配它,以在导航期间进行智能打勾。(直接翻译,感觉用的不多)。

AutoMinorLocator

轴为线性且主刻度线等距分布时,副刻度线定位器。将主要刻度间隔细分为指定数量的次要间隔,根据主要间隔默认为4或5。

看完是不是觉得小编啥都没说,越看越糊涂?其实我也是。下面 我们就将每种刻度定位(Locator)可视化展现出来,有助于我们直接观察。主要代码如下:

//Filename Locator.python

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.ticker as ticker

plt.rcParams['font.family'] = "Times New Roman"

def setup(ax, title):

"""Set up common parameters for the Axes in the example."""

# only show the bottom spine

ax.yaxis.set_major_locator(ticker.NullLocator())

ax.spines['right'].set_color('none')

ax.spines['left'].set_color('none')

ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')

ax.tick_params(which='major', width=1.00, length=5)

ax.tick_params(which='minor', width=0.75, length=2.5)

ax.set_xlim(0, 5)

ax.set_ylim(0, 1)

ax.text(0.0, 0.2, title, transform=ax.transAxes,

fontsize=14, fontname='Monospace', color='tab:blue')

fig, axs = plt.subplots(8, 1, figsize=(8, 6),dpi=200)

# Null Locator

setup(axs[0], title="NullLocator()")

axs[0].xaxis.set_major_locator(ticker.NullLocator())

axs[0].xaxis.set_minor_locator(ticker.NullLocator())

# Multiple Locator

setup(axs[1], title="MultipleLocator(0.5)")

axs[1].xaxis.set_major_locator(ticker.MultipleLocator(0.5))

axs[1].xaxis.set_minor_locator(ticker.MultipleLocator(0.1))

# Fixed Locator

setup(axs[2], title="FixedLocator([0, 1, 5])")

axs[2].xaxis.set_major_locator(ticker.FixedLocator([0, 1, 5]))

axs[2].xaxis.set_minor_locator(ticker.FixedLocator(np.linspace(0.2, 0.8, 4)))

# Linear Locator

setup(axs[3], title="LinearLocator(numticks=3)")

axs[3].xaxis.set_major_locator(ticker.LinearLocator(3))

axs[3].xaxis.set_minor_locator(ticker.LinearLocator(31))

# Index Locator

setup(axs[4], title="IndexLocator(base=0.5, offset=0.25)")

axs[4].plot(range(0, 5), [0]*5, color='white')

axs[4].xaxis.set_major_locator(ticker.IndexLocator(base=0.5, offset=0.25))

# Auto Locator

setup(axs[5], title="AutoLocator()")

axs[5].xaxis.set_major_locator(ticker.AutoLocator())

axs[5].xaxis.set_minor_locator(ticker.AutoMinorLocator())

# MaxN Locator

setup(axs[6], title="MaxNLocator(n=4)")

axs[6].xaxis.set_major_locator(ticker.MaxNLocator(4))

axs[6].xaxis.set_minor_locator(ticker.MaxNLocator(40))

# Log Locator

setup(axs[7], title="LogLocator(base=10, numticks=15)")

axs[7].set_xlim(10**3, 10**10)

axs[7].set_xscale('log')

axs[7].xaxis.set_major_locator(ticker.LogLocator(base=10, numticks=15))

plt.tight_layout()

plt.savefig(r'F:\DataCharm\学术图表绘制\Python-matplotlib\matplotlib_locators',width=6,height=4,

dpi=900,bbox_inches='tight')

plt.show()

可视化结果如下:

图中红框标出的为 Tick locators 较常用的的几种形式。

Tick formatters

Tick formatters 设置刻度标签形式,主要对绘图刻度标签定制化需求时,matplotlib 可支持修改的刻度标签形式如下:

定位器

解释说明

NullFormatter

刻度线上没有标签。

IndexFormatter

从标签列表中设置刻度标签。

FixedFormatter

手动设置标签字符串。

FuncFormatter

用户定义的功能设置标签。

StrMethodFormatter

使用字符串方法设置刻度标签。

FormatStrFormatter

使用旧式的sprintf格式字符串。

ScalarFormatter

标量的默认格式:自动选择格式字符串。

LogFormatter

Log对数形式的刻度标签。

LogFormatterExponent

使用exponent=log_base(value)形式的刻度标签。

LogFormatterMathtext

使用Math文本使用exponent = log_base(value)格式化对数轴的值。

LogitFormatter

概率格式器。

PercentFormatter

将标签格式化为百分比。

还是老样子,我们可视化展示来看,这样就对每一个刻度标签形式有明确的理解,代码如下:

// filename Tick formatters.python

import matplotlib.pyplot as plt

from matplotlib import ticker

def setup(ax, title):

"""Set up common parameters for the Axes in the example."""

# only show the bottom spine

ax.yaxis.set_major_locator(ticker.NullLocator())

ax.spines['right'].set_color('none')

ax.spines['left'].set_color('none')

ax.spines['top'].set_color('none')

# define tick positions

ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))

ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))

ax.xaxis.set_ticks_position('bottom')

ax.tick_params(which='major', width=1.00, length=5)

ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10)

ax.set_xlim(0, 5)

ax.set_ylim(0, 1)

ax.text(0.0, 0.2, title, transform=ax.transAxes,

fontsize=14, fontname='Monospace', color='tab:blue')

fig0, axs0 = plt.subplots(2, 1, figsize=(8, 2))

fig0.suptitle('Simple Formatting')

setup(axs0[0], title="'{x} km'")

axs0[0].xaxis.set_major_formatter('{x} km')

setup(axs0[1], title="lambda x, pos: str(x-5)")

axs0[1].xaxis.set_major_formatter(lambda x, pos: str(x-5))

fig0.tight_layout()

# The remaining examples use Formatter objects.

fig1, axs1 = plt.subplots(7, 1, figsize=(8, 6))

fig1.suptitle('Formatter Object Formatting')

# Null formatter

setup(axs1[0], title="NullFormatter()")

axs1[0].xaxis.set_major_formatter(ticker.NullFormatter())

# StrMethod formatter

setup(axs1[1], title="StrMethodFormatter('{x:.3f}')")

axs1[1].xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.3f}"))

# FuncFormatter can be used as a decorator

@ticker.FuncFormatter

def major_formatter(x, pos):

return f'[{x:.2f}]'

setup(axs1[2], title='FuncFormatter("[{:.2f}]".format')

axs1[2].xaxis.set_major_formatter(major_formatter)

# Fixed formatter

setup(axs1[3], title="FixedFormatter(['A', 'B', 'C', ...])")

# FixedFormatter should only be used together with FixedLocator.

# Otherwise, one cannot be sure where the labels will end up.

positions = [0, 1, 2, 3, 4, 5]

labels = ['A', 'B', 'C', 'D', 'E', 'F']

axs1[3].xaxis.set_major_locator(ticker.FixedLocator(positions))

axs1[3].xaxis.set_major_formatter(ticker.FixedFormatter(labels))

# Scalar formatter

setup(axs1[4], title="ScalarFormatter()")

axs1[4].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))

# FormatStr formatter

setup(axs1[5], title="FormatStrFormatter('#%d')")

axs1[5].xaxis.set_major_formatter(ticker.FormatStrFormatter("#%d"))

# Percent formatter

setup(axs1[6], title="PercentFormatter(xmax=5)")

axs1[6].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))

fig1.tight_layout()

plt.show()

结果如下:

以上就是对matplotlib 的刻度位置和刻度标签形式的介绍,大家也只需了解一两个常用的即可,其他用时再到matplotlib查找即可。下面我们将通过几个例子讲解刻度中用的最多的「时间刻度形式」的设置。

时间刻度形式

默认时间格式

这里我们使用自己生成的数据进行绘制,详细代码如下:

//filename time_tick01.python

//@by DataCharm

import matplotlib.pyplot as plt

import matplotlib.dates as mdates

from datetime import datetime

plt.rcParams['font.family'] = 'Times New Roman'

dates=[20200601,20200602,20200603,20200604,20200605,20200606,20200607,20200608]

sales=[20,30,40,60,50,70,40,30]

#将dates改成日期格式

x= [datetime.strptime(str(d), '%Y%m%d').date() for d in dates]

#绘图

fig,ax = plt.subplots(figsize=(4,2.5),dpi=200)

ax.plot(x,sales,lw=2,color='#24C8B0',marker='o',ms=6, mec='#FD6174',mew=1.5, mfc='w')

#设置时间刻度轴旋转角度:使用ax.tick_params

# ax.tick_params(axis='x',direction='in',labelrotation=40,labelsize=8,pad=5) #选择x轴

# ax.tick_params(axis='y',direction='in',labelsize=8,pad=5)

#或者如下设置

for label in ax.get_xticklabels():

label.set_rotation(40)

label.set_horizontalalignment('right')

ax.text(.85,.05,'\nVisualization by DataCharm',transform = ax.transAxes,

ha='center', va='center',fontsize = 4,color='black',fontweight='bold',family='Roboto Mono')

#ax.tick_params(pad=5)

plt.savefig("F:\DataCharm\学术图表绘制\Python-matplotlib\matplotlib_time_ticks_set01.png",width=8,height=5,dpi=900,bbox_inches='tight')

#显示图像

plt.show()

可视化结果如下:

这里我们可以发现,虽然我们设置了旋转角度(具体设置方式看绘图代码),但也不可避免导致影响美观。接下来我们使用半自动方式定制时间刻度形式。

使用DayLocator、HourLocator等时间刻度定位器

具体代码如下:

//filename time_tick02.python

//@by DataCharm

import matplotlib.pyplot as plt

import matplotlib.dates as mdates

from datetime import datetime

dates=[20200601,20200602,20200603,20200604,20200605,20200606,20200607,20200608]

sales=[20,30,40,60,50,70,40,30]

#将dates改成日期格式

x= [datetime.strptime(str(d), '%Y%m%d').date() for d in dates]

#绘图

fig,ax = plt.subplots(figsize=(4,2.5),dpi=200)

ax.plot(x,sales,lw=2,color='#24C8B0',marker='o',ms=6, mec='#FD6174',mew=1.5, mfc='w')

#设置x轴主刻度格式

day =  mdates.DayLocator(interval=2) #主刻度为天,间隔2天

ax.xaxis.set_major_locator(day) #设置主刻度

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

#设置副刻度格式

hoursLoc = mdates.HourLocator(interval=20) #为20小时为1副刻度

ax.xaxis.set_minor_locator(hoursLoc)

ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H'))

#设置主刻度旋转角度和刻度label刻度间的距离pad

ax.tick_params(which='major',axis='x',labelrotation=10,labelsize=9,length=5,pad=10)

ax.tick_params(which='minor',axis='x',labelsize=8,length=3)

ax.tick_params(axis='y',labelsize=9,length=3,direction='in')

ax.text(.85,.05,'\nVisualization by DataCharm',transform = ax.transAxes,

ha='center', va='center',fontsize = 4,color='black',fontweight='bold',family='Roboto Mono')

plt.savefig("F:\DataCharm\学术图表绘制\Python-matplotlib\matplotlib_time_ticks_set03.png",width=8,height=5,dpi=900,

bbox_inches='tight')

#显示图像

plt.show()

可视化结果如下:

可以发现(如图中红色圆圈所示),我们分别设置了主副刻度形式且设置了时间间隔。接下来我们看一个一键设置时间刻度形式的方式。

使用ConciseDateFormatter 时间刻度形式

绘图代码如下:

//filename time_tick_ConciseDate.python

//@by DataCharm

import datetime

import matplotlib.pyplot as plt

import matplotlib.dates as mdates

import numpy as np

dates=[20200601,20200602,20200603,20200604,20200605,20200606,20200607,20200608]

sales=[20,30,40,60,50,70,40,30]

#将dates改成日期格式

x= [datetime.strptime(str(d), '%Y%m%d').date() for d in dates]

fig,ax = plt.subplots(figsize=(4,2.5),dpi=200)

locator = mdates.AutoDateLocator(minticks=2, maxticks=7)

formatter = mdates.ConciseDateFormatter(locator)

ax.plot(x,sales,lw=2,color='#24C8B0',marker='o',ms=6, mec='#FD6174',mew=1.5, mfc='w')

ax.xaxis.set_major_locator(locator)

ax.xaxis.set_major_formatter(formatter)

ax.text(.85,.05,'\nVisualization by DataCharm',transform = ax.transAxes,

ha='center', va='center',fontsize = 4,color='black',fontweight='bold',family='Roboto Mono')

plt.savefig("F:\DataCharm\学术图表绘制\Python-matplotlib\matplotlib_time_ticks_set02.png",width=8,height=5,dpi=900,bbox_inches='tight')

plt.show()

可以看出(如下图红色圆圈所示),这种方法可以完美解决时间刻度拥挤的现象,而且在对多时间或者一天内多小时也能够完美解决。

直接更改刻度标签名称(tickslabel)

最后这种方法就比较简单粗暴了,我们直接使用ax.set_xticklabels() 命名刻度标签。代码如下:

//filename time_tick_04.python

//@by DataCharm

import matplotlib.pyplot as plt

import matplotlib.dates as mdates

from datetime import datetime

dates=[20200601,20200602,20200603,20200604,20200605,20200606,20200607,20200608]

sales=[20,30,40,60,50,70,40,30]

date_label = ['2020-0601','2020-06-02','20200603','2020-604','2020605','20200606','2020-0607',

'2020-0608']

#将dates改成日期格式

x= [datetime.strptime(str(d), '%Y%m%d').date() for d in dates]

#绘图

fig,ax = plt.subplots(figsize=(4,2.5),dpi=200)

ax.plot(x,sales,lw=2,color='#24C8B0',marker='o',ms=6, mec='#FD6174',mew=1.5, mfc='w')

#自定义刻度label

ax.set_xticklabels(date_label)

#设置主刻度旋转角度和刻度label于刻度间的距离pad

ax.tick_params(axis='x',labelrotation=15,labelsize=8,length=5,pad=5)

ax.tick_params(axis='y',labelsize=9,length=3,direction='in')

ax.text(.85,.05,'\nVisualization by DataCharm',transform = ax.transAxes,

ha='center', va='center',fontsize = 4,color='black',fontweight='bold',family='Roboto Mono')

plt.savefig("F:\DataCharm\学术图表绘制\Python-matplotlib\matplotlib_time_ticks_set04.png",width=8,height=5,dpi=900,

bbox_inches='tight')

#显示图像

plt.show()

结果如下(图中红色圆圈内),这里我随意定义刻度labels形式。

总结

本篇推文首先简单介绍了Python-matplotlib刻度(ticker) 设置位置和形式,然后具体介绍了时间刻度设置的几种方法,希望能够给大家解决时间刻度设置带来灵感。就本人绘图而言,matplotlib时间刻度设置还是采用ConciseDateFormatter方法最为方便,当然,如果定制化需求较高,大家也可以采用直接设置刻度的方法。

加入我们的知识星球【Python大数据分析】

爱上数据分析!

· 往期精选 ·

Python大数据分析

data creates value

扫码关注我们

python 大数据量绘图_Matplotlib绘图遇到时间刻度就犯难?现在,一次性告诉你四种方法...相关推荐

  1. Matpotlib绘图遇到时间刻度就犯难?现在,一次性告诉你四种方法

    公众号后台回复"图书",了解更多号主新书内容 作者:宁海涛 来源:DataCharm 点击蓝字 关注我们 最近有小伙伴私信我关于matplotlib时间类型刻度的设置问题,第一感觉 ...

  2. python设置刻度间隔不等_Matplotlib绘图遇到时间刻度就犯难?现在,一次性告诉你四种方法...

    最近有小伙伴私信我关于matplotlib时间类型刻度的设置问题,第一感觉就是官网有好多例子介绍啊 转念一想,在实际应用中类似设置还挺多和好多小伙伴询问,那么本期就就简单介绍下Python-matpl ...

  3. mysql 主键重复则覆盖_mysql insert插入时实现如果数据表中主键重复则更新,没有重复则插入的四种方法...

    个人实例: INSERT INTO w_dashboard(dashboard_name, content, createTime) VALUES("aa","cc&qu ...

  4. python能处理多大的数据-Python 适合大数据量的处理吗?

    python 能处理数据库中百万行级的数据吗? 处理大规模数据时有那些常用的python库,他们有什么优缺点?适用范围如何? 王守崑,推荐系统,数据挖掘 需要澄清两点之后才可以比较全面的看这个问题: ...

  5. 【Python开发】Python 适合大数据量的处理吗?

    Python 适合大数据量的处理吗? python 能处理数据库中百万行级的数据吗? 处理大规模数据时有那些常用的python库,他们有什么优缺点?适用范围如何? 需要澄清两点之后才可以比较全面的看这 ...

  6. Python +大数据-知行教育(四)-意向用户主题看板_全量流程

    Python +大数据-知行教育(四)-意向用户主题看板_全量流程 5. 意向用户主题看板_全量流程 5.1 需求分析 主要分析什么内容:1) 每一个需求涉及到那些维度, 那些直白2) 每一个需求涉及 ...

  7. 财务大数据比赛有python吗-Python大数据与机器学习之NumPy初体验

    本文是Python大数据与机器学习系列文章中的第6篇,将介绍学习Python大数据与机器学习所必须的NumPy库. 通过本文系列文章您将能够学到的知识如下: 应用Python进行大数据与机器学习 应用 ...

  8. 零起点Python大数据与量化交易

    零起点Python大数据与量化交易 第1章 从故事开始学量化 1 1.1 亿万富翁的"神奇公式" 2 1.1.1 案例1-1:亿万富翁的"神奇公式" 2 1.1 ...

  9. Python大数据综合应用 :零基础入门机器学习、深度学习算法原理与案例

    机器学习.深度学习算法原理与案例实现暨Python大数据综合应用高级研修班 一.课程简介 课程强调动手操作:内容以代码落地为主,以理论讲解为根,以公式推导为辅.共4天8节,讲解机器学习和深度学习的模型 ...

最新文章

  1. 移动端丨-webkit-overflow-scrolling:touch属性导致页面卡住
  2. c语言编程员工管理的代码,员工信息管理完整(含附源代码).doc
  3. LeetCode Add Two Numbers II(栈)
  4. 重要头文件: cc430x613x.h
  5. [No0000176]Git常用命令速查表(收藏大全)
  6. Linux -sed
  7. 谷歌眼镜Mirror app开发之简单新闻浏览页面
  8. Linux系统压力测试工具stress
  9. ps将psd等比缩放、等份切片、psd转为jpg、Cutterman、切片方法、旋转方法(编辑)
  10. CF816B Karen and Coffee题解
  11. windows c语言 创建目录,C语言创建删不掉的文件夹
  12. MySQL数据库web客户端管理工具软件
  13. IBL 漫反射辐照度
  14. Linux启动定时任务
  15. [软件人生]关于认知,能力的思考——中国城市里的无知现象片段补充之一
  16. 论文阅读 - 《Exposing DeepFake Videos By Detecting Face Warping Artifacts》
  17. 菜鸟的最后一篇php教程
  18. 解决虚拟机卡死且无法强制结束进程的问题
  19. Rulo扫地机器人app_传感器升级+支持APP:Panasonic 松下 推出 新款 RULO 扫地机器人 MC-RS800...
  20. 联想wh系列服务器,ThinkAgile WH 系列

热门文章

  1. 上海宏满实业档案管理规范化
  2. 羊皮卷之六-今天我要学会控制情绪(中英对照)
  3. ai画面怎么调大小_ai怎么调整画布尺寸? ai设置画布大小的两种方法
  4. 易筋经韦驮劲十二势图及拳谱
  5. JAVA毕设项目网上拍卖系统(java+VUE+Mybatis+Maven+Mysql)
  6. “伪造证据”英语怎么说
  7. Android如何实现简易登陆注册实例源码
  8. 三国志13pk版登录武将输入中文名方法与更改图像详解
  9. 十二种值得深交的男生和十一种值得深交的女生
  10. BetterAndBetter--Mac全局手势软件