最近有小伙伴私信我关于matplotlib时间类型刻度的设置问题,第一感觉就是官网有好多例子介绍啊
转念一想,在实际应用中类似设置还挺多和好多小伙伴询问,那么本期就就简单介绍下Python-matplotlib「刻度(ticker)」 的使用方法,并结合具体例子讲解时间刻度设置问题,使小伙伴们定制化刻度不再烦恼。本期推文只要涉及知识点如下:Tick locators 刻度位置介绍
Tick formatters 刻度形式介绍
时间刻度的设置
位置(Locator)和形式 (Formatter)
Tick Locator
Tick Locator主要设置刻度位置,这在我的绘图教程中主要是用来设置副刻度(minor),而Formatter则是主要设置刻度形式。Matplotlib对这两者则有着多种用法,其中Locator的子类主要如下:定位器解释说明
看完是不是觉得小编啥都没说,越看越糊涂?其实我也是。下面 我们就将每种刻度定位(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(tic