Matplotlib将轴显示为二进制 [英] Matplotlib display axis as binary
问题描述
我正在尝试用二进制标记图形的x轴,而不是Python 2.7中的float值.我正在尝试使用 FormatStrFormatter('%b')
,它根据
I'm attempting to label the x-axis of my graph in binary instead of float values in Python 2.7. I'm attempting to use FormatStrFormatter('%b')
which according to the documentation provided by the Python Software Foundation should work. I'd also like all the binary strings to be the same length of characters. I've also consulted this link.
The error I'm getting is:
ValueError: unsupported format character 'b' (0x62) at index 1
I've tried to do it like:
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()
You may use a StrMethodFormatter
, this works well also with the b
option.
StrMethodFormatter("{x:b}")
However leading zeros require to know how many of them you expect (here 7).
StrMethodFormatter("{x:07b}")
Complete example:
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()
这篇关于Matplotlib将轴显示为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!