python - 使用 loglocator 和不同的 x 和 y 限制时,Matplotlib 日志图不显示所有主要和次要刻度
问题描述
我正在制作一个日志图并使用 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
文档:
请注意,不应跨多个轴使用相同的定位器,因为定位器存储对轴数据和视图限制的引用。
因此,对于您的绘图,当您重用 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()
推荐阅读
- mysql - MySQL 错误:在这个位置无效,需要一个标识符
- node-sass - 您正在尝试使用“scss”。缺少节点萨斯
- oracle - 为数据库中的插入记录创建文件
- ms-access - 日期格式 MS Query vs VBA
- html - 弹性容器中的项目没有得到边距/在容器中均匀对齐
- firebase - Flutter:如何设置 Stream 和 Provider
- javascript - 如何在反应播放器(reactjs)中禁用 YouTube 上下文菜单?
- jquery - 如何使用 jQuery 附加自定义选项值?
- c# - 来自控制台应用程序中主要方法的 DI
- android - Hilt:带有抽象 Activity 的抽象方法抛出错误