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

时间:2022-07-25
本文章向大家介绍Matpotlib绘图遇到时间刻度就犯难?现在,一次性告诉你四种方法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
作者:宁海涛

来源:DataCharm

点击蓝字 关注我们

最近有小伙伴私信我关于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-matplotlibmatplotlib_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-matplotlibmatplotlib_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-matplotlibmatplotlib_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-matplotlibmatplotlib_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-matplotlibmatplotlib_time_ticks_set04.png",width=8,height=5,dpi=900,
            bbox_inches='tight')
#显示图像
plt.show()

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

总结

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