Matplotlib显示坐标轴为二进制

3
我试图在Python 2.7中使用二进制标签而不是浮点值来标记我的图表的x轴。我尝试使用FormatStrFormatter('%b'),根据由Python Software Foundation提供的文档,这应该可以工作。我还希望所有二进制字符串的长度都相同。我还参考了这个链接
我收到的错误信息是:

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()

在Python 3.6中,'%b' % 12会抛出错误,而'%x''%o'则不会。你确定'%b'是%格式规范的一部分吗? - FHTMitchell
是的。十六进制(x)可以正常工作。 - Number1
那并没有回答我的问题——MatPlotLib不支持二进制%b格式,因为str.__mod__函数不支持。看一下你错误信息的最后两行:return self.fmt % x ValueError: unsupported format character 'b' (0x62) at index 1 - FHTMitchell
它应该具有 b 作为二进制位于这两个定义之上。 - Number1
2个回答

5
您可以使用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()

enter image description here


2

试试这个:

from matplotlib.ticker import FuncFormatter
…
ax.yaxis.set_major_formatter(FuncFormatter("{:b}".format))

它应该在Python 3.5中工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接