Matplotlib使用LogLocator绘制双对数图轴限不同时主副刻度缺失
问题原因
该异常由复用同一个LogLocator实例给x、y两个不同取值范围的轴导致。matplotlib.ticker.LogLocator属于带内部状态的对象,当它被绑定到第一个轴(示例中为y轴)时,会根据y轴的取值范围计算并缓存刻度位置,后续再绑定到取值范围不同的x轴时,不会重新适配新的轴范围,最终出现刻度、刻度标签丢失的问题。
解决方案
不要跨轴复用Locator实例,为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') # 单独为y轴创建主、副刻度定位器 y_locmaj = matplotlib.ticker.LogLocator(base=10,numticks=100) y_locmin = matplotlib.ticker.LogLocator(base=10,subs=np.arange(2, 10) * .1,numticks=100) ax.yaxis.set_major_locator(y_locmaj) ax.yaxis.set_minor_locator(y_locmin) ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter()) # 单独为x轴创建主、副刻度定位器 x_locmaj = matplotlib.ticker.LogLocator(base=10,numticks=100) x_locmin = matplotlib.ticker.LogLocator(base=10,subs=np.arange(2, 10) * .1,numticks=100) ax.xaxis.set_major_locator(x_locmaj) ax.xaxis.set_minor_locator(x_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()
运行上述代码后x、y轴的主副刻度都会正常显示,不会再出现刻度缺失的问题。
内容的提问来源于stack exchange,提问作者SebaMarino
相关产品推荐
相关产品推荐

