python - Matplotlib 半对数图 : minor tick marks are gone when range is large

标签 python matplotlib

做半对数图(y为对数)时,y轴上的小刻度线(十进制8个)自动出现,但似乎当轴范围超过10**10时,它们就消失了。我尝试了很多方法迫使他们回来,但都无济于事。他们可能会离开大范围以避免过度拥挤,但应该有选择吗?

最佳答案

matplotlib >= 2.0.2 的解决方案

让我们考虑下面的例子

enter image description here

由这段代码产生:

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

y = np.arange(12)
x = 10.0**y

fig, ax=plt.subplots()
ax.plot(x,y)
ax.set_xscale("log")
plt.show()

次要刻度标签确实消失了,通常显示它们的方法(如 plt.tick_params(axis='x', which='minor'))失败了。

第一步是在轴上显示 10 的所有次方,

locmaj = matplotlib.ticker.LogLocator(base=10,numticks=12) 
ax.xaxis.set_major_locator(locmaj)

enter image description here

诀窍是将 numticks 设置为等于或大于刻度数的数字(即在本例中为 12 或更高)。

然后,我们可以添加次要的刻度标签作为

locmin = matplotlib.ticker.LogLocator(base=10.0,subs=(0.2,0.4,0.6,0.8),numticks=12)
ax.xaxis.set_minor_locator(locmin)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

enter image description here

请注意,我将其限制为每十年包含 4 个小刻度(同样可以使用 8 个,但在此示例中会使坐标轴过度拥挤)。另请注意,numticks 再次(非常不直观地)为 12 或更大。

最后,我们需要为次要刻度使用 NullFormatter(),以免为它们显示任何刻度标签。

matplotlib 2.0.0 的解决方案

以下在 matplotlib 2.0.0 或更低版本中有效,但在 matplotlib 2.0.2 中无效。

让我们考虑下面的例子

enter image description here

由这段代码产生:

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

y = np.arange(12)
x = 10.0**y

fig, ax=plt.subplots()
ax.plot(x,y)
ax.set_xscale("log")
plt.show()

次要刻度标签确实消失了,通常显示它们的方法(如 plt.tick_params(axis='x', which='minor'))失败了。

第一步是在轴上显示 10 的所有次方,

locmaj = matplotlib.ticker.LogLocator(base=10.0, subs=(0.1,1.0, ))
ax.xaxis.set_major_locator(locmaj)

enter image description here

然后,我们可以添加次要的刻度标签作为

locmin = matplotlib.ticker.LogLocator(base=10.0, subs=(0.1,0.2,0.4,0.6,0.8,1,2,4,6,8,10 )) 
ax.xaxis.set_minor_locator(locmin)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

enter image description here

请注意,我将其限制为每十年包含 4 个小刻度(同样可以使用 8 个,但在此示例中会使坐标轴过度拥挤)。另请注意 - 这可能是这里的关键 - subs 参数给出了一个列表范围超过二十年而不是一个。

最后,我们需要为次要刻度使用 NullFormatter(),以免为它们显示任何刻度标签。

关于python - Matplotlib 半对数图 : minor tick marks are gone when range is large,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44078409/

相关文章:

python - 如何更新 matplotlib 中 imshow 的范围?

python - 使用 BeautifulSoup 查找所选选项

python - 如何使用bind动态更新Kivy Label的文本属性

python - 使用 fft2 reshape RGB 滤镜

python - 增加 matplotlib 注释文本中的行间距

python - 过滤数据框的 Pandas 直方图

python - Pandas 转换多索引头

python - 此错误的起因

Python:绘制具有重复条目的字符串数组与不带 for 循环的 float

python - Matplotlib:将不同的散点标记分组在同一个图例下