我试图用二进制而不是 Python 2.7 中的浮点值来标记图形的 x 轴。我正在尝试根据 documentation 使用 FormatStrFormatter('%b')
Python Software Foundation 提供的应该可以工作。我还希望所有二进制字符串的字符长度相同。我也咨询过这个link .
我得到的错误是:
ValueError: unsupported format character 'b' (0x62) at index 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()
最佳答案
您可以使用 StrMethodFormatter
,这也适用于 b
选项。
StrMethodFormatter("{x:b}")
但是前导零需要知道您期望有多少(这里是 7)。
StrMethodFormatter("{x:07b}")
完整示例:
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()
关于python - Matplotlib 将轴显示为二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51446033/