自定义坐标轴刻度

阅读: 4105     评论:0

Matplotlib图形对象具有层级关系。Figure对象其实就是一个盛放图形元素的盒子box,每个figure都会包含一个或多个axes对象,而每个axes对象又会包含其它表示图形内容的对象,比如xais和yaxis,也就是x轴和y轴。

  • 主要刻度和次要刻度

每个坐标轴都有主要刻度和次要刻度,主要刻度往往更大或者突出显示,而次要刻度往往更小,一般不直接显示。

下面是一个对数坐标轴,可以看到次要刻度:

ax = plt.axes(xscale='log', yscale='log')

我们发现每个主要刻度都显示未一个较大的刻度线和标签,而次要刻度都显示为一个较小的刻度线,并且不现实标签。

img

每种刻度线都包含一个坐标轴定位器(locator)和格式生成器(formatter),可以通过下面的方法查看:

>>> ax.xaxis.get_major_locator()
<matplotlib.ticker.LogLocator at 0x276ff49db38>
>>> ax.xaxis.get_major_formatter()
<matplotlib.ticker.LogFormatterSciNotation at 0x276ff49d978>

>>> ax.xaxis.get_minor_locator()
<matplotlib.ticker.LogLocator at 0x276ff49d940>
>>> ax.xaxis.get_minor_formatter()
<matplotlib.ticker.LogFormatterSciNotation at 0x276ff493320>

我们可以发现,针对x或y轴,针对主要和次要,针对定位器和格式器,分别有不同的对象来处理。

  • 隐藏刻度与标签

如果我们想隐藏刻度或标签,就要着落在locator和formatter这两大属性上了:

ax = plt.axes()
x = np.linspace(0,10,100)
ax.plot(np.sin(x))

ax.yaxis.set_major_locator(plt.NullLocator())
ax.xaxis.set_major_formatter(plt.NullFormatter())

img

可以看出,没有locator,刻度和标签都会被隐藏起来;没有formatter,隐藏标签,但刻度还存在。

  • 设置刻度数量

默认情况下,matplotlib会自动帮我们调节刻度的数量,但有时候也需要我们自定义刻度数量:

fig, ax = plt.subplots(4, 4, sharex=True, sharey=True)
for axi in ax.flat:
    axi.xaxis.set_major_locator(plt.MaxNLocator(4))
    axi.yaxis.set_major_locator(plt.MaxNLocator(4))

img


 patch 风格样式展示 

评论总数: 0


点击登录后方可评论