3

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()
Number1
  • 391
  • 2
  • 4
  • 22
  • `'%b' % 12` throws an error in python 3.6 for me whereas `'%x'` and `'%o'` don't. Are you sure it's part of the % format spec? – FHTMitchell Jul 20 '18 at 15:41
  • Yes. Hexadecimal (x) works fine. – Number1 Jul 20 '18 at 15:48
  • ? That didn't answer my question -- MatPlotLib doesn't support the binary `%b` spec because the `str.__mod__` function doesn't. Look at the last 2 lines of your error: `return self.fmt % x ValueError: unsupported format character 'b' (0x62) at index 1` – FHTMitchell Jul 20 '18 at 15:48
  • It should have as b for binary is above those two definitions. – Number1 Jul 20 '18 at 15:49

2 Answers2

5

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

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
2

Try this:

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

It should work in Python 3.5.

Florian Weimer
  • 32,022
  • 3
  • 48
  • 92