使用 loglocator 和不同的 x 和 y 限制时,Matplotlib log log plot 不显示所有主要和次要刻度

Matplotlib log log plot not displaying all major and minor ticks when using loglocator and different x and y limits

我正在制作对数对数图并使用 matplotlib。我正在使用 loglocator 来确保显示相关的主要和次要刻度。但是,我注意到当 x 和 y 限制不同时,一些刻度和刻度标签会丢失:

下面是一个产生这种不良行为的简单示例。任何帮助将不胜感激。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib

Npoints=100
xs=np.logspace(-8,0, 100)
ys=xs

fig=plt.figure(figsize=(4,3))
ax=fig.add_subplot(111)
ax.plot(xs, ys)
ax.set_xscale('log')
ax.set_yscale('log')

locmaj = matplotlib.ticker.LogLocator(base=10,numticks=100) 
locmin = matplotlib.ticker.LogLocator(base=10,subs=np.arange(2, 10) * .1,numticks=100) # subs=(0.2,0.4,0.6,0.8)

ax.yaxis.set_major_locator(locmaj)
ax.yaxis.set_minor_locator(locmin)
ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

ax.xaxis.set_major_locator(locmaj)
ax.xaxis.set_minor_locator(locmin)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

ax.set_xlim(1.0e-3, 1.0)
ax.set_ylim(1.0e-8, 1.0)

plt.show()

一般来说,Locator 个实例不应在不同的轴上重复使用。来自 Locator docs:

Note that the same locator should not be used across multiple Axis because the locator stores references to the Axis data and view limits.

因此,对于您的绘图,当您在 x 轴上重复使用定位器时,它们会以不希望的方式修改 y 轴上的刻度。解决这个问题。您应该为每个 LogLocator 创建一个单独的实例,以便在每个轴上使用。例如:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib

Npoints=100
xs=np.logspace(-8,0, 100)
ys=xs

fig=plt.figure(figsize=(4,3))
ax=fig.add_subplot(111)
ax.plot(xs, ys)
ax.set_xscale('log')
ax.set_yscale('log')

locmajx = matplotlib.ticker.LogLocator(base=10,numticks=100) 
locminx = matplotlib.ticker.LogLocator(base=10,subs=np.arange(2, 10) * .1,numticks=100) # subs=(0.2,0.4,0.6,0.8)
locmajy = matplotlib.ticker.LogLocator(base=10,numticks=100) 
locminy = matplotlib.ticker.LogLocator(base=10,subs=np.arange(2, 10) * .1,numticks=100) # subs=(0.2,0.4,0.6,0.8)

ax.yaxis.set_major_locator(locmajy)
ax.yaxis.set_minor_locator(locminy)
ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

ax.xaxis.set_major_locator(locmajx)
ax.xaxis.set_minor_locator(locminx)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

ax.set_xlim(1.0e-3, 1.0)
ax.set_ylim(1.0e-8, 1.0)

plt.show()