Matplotlib 将轴显示为二进制

Num*_*er1 3 python graphics matplotlib python-2.7

我试图用二进制标记图形的 x 轴,而不是 Python 2.7 中的浮点值。我正在尝试FormatStrFormatter('%b')根据Python 软件基金会提供的文档使用它。我还希望所有二进制字符串的字符长度相同。我也咨询过这个链接

我得到的错误是:

ValueError: 不支持的格式字符 'b' (0x62) 在索引 1

我试过这样做:

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

fig, ax = plt.subplots()

ax.yaxis.set_major_formatter(FormatStrFormatter('%b'))
ax.yaxis.set_ticks(np.arange(0, 110, 10))

x = np.arange(1, 10, 0.1)
plt.plot(x, x**2)
plt.show()
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 5

您可以使用 a StrMethodFormatter,这也适用于该b选项。

StrMethodFormatter("{x:b}")
Run Code Online (Sandbox Code Playgroud)

然而,前导零需要知道您期望有多少个零(此处为 7)。

StrMethodFormatter("{x:07b}")
Run Code Online (Sandbox Code Playgroud)

完整示例:

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

fig, ax = plt.subplots()

ax.yaxis.set_major_formatter(StrMethodFormatter("{x:07b}"))
ax.yaxis.set_ticks(np.arange(0, 110, 10))

x = np.arange(1, 10, 0.1)
plt.plot(x, x**2)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明