如何在具有对数刻度和添加自定义网格线的同时在二进制上显示轴

how to display axis on binary while having log scale and adding custom grid lines

我从这里收集了不同的代码片段。我的代码如下所示:

fig, ax = plt.subplots()
ax.set_yscale('log', base=2)
ax.yaxis.set_major_formatter(lambda x, pos: f"{int(x):12b}")
data = np.arange(100)
ticks = [2, 3, 4, 13]
plt.plot(data,data)
ax.set_yticks(ticks, minor=True)
ax.yaxis.grid(True, which='minor')
plt.show()

因此,目标是以对数标度绘制,以二进制显示 y 轴并添加自定义 ticks。该代码工作完美,除了 ticks 以十进制显示。如下图所示。我希望它们也是二进制的。我试图修复它,但我真的不知道如何修复。我尝试设置 ax.set_ticks([lambda x: f"{int(x):12b}"], minor=True) 但这没有用。如果有人可以帮助我,我将不胜感激。

您需要 ax.yaxis.set_minor_formatter(...) 的小刻度线。您会注意到主要刻度线和次要刻度线并没有完全对齐。这是由于刻度长度,可以通过 ax.tick_params(..., length=...).

强制相等
from matplotlib import pyplot as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(15, 4))
for ax in (ax1, ax2):
    ax.set_yscale('log', base=2)
    ax.yaxis.set_major_formatter(lambda x, pos: f"{int(x):12b}")
    ax.yaxis.set_minor_formatter(lambda x, pos: f"{int(x):12b}")
    data = np.arange(100)
    ticks = [2, 3, 4, 13]
    ax.plot(data,data)
    ax.set_yticks(ticks, minor=True)
    ax.yaxis.grid(True, which='minor')
ax1.set_title('default tick lengths')
ax2.set_title('equal tick lengths')
ax2.tick_params(axis='y', which='both', length=2)
plt.show()

PS:请注意,当次要报价非常接近主要报价时,它们会被抑制。因此,2 和 4 的网格线不可见。您可以通过稍微移动它们来解决这个问题。例如

ticks = [2.001, 3.001, 4.001, 13.001]

或者您可以更改主要和次要刻度的作用,对次要刻度使用 LogLocator

from matplotlib.ticker import LogLocator

ax.yaxis.set_minor_locator(LogLocator(base=2))
ax.set_yticks(ticks)
ax.yaxis.grid(True, which='major')