Reputation: 450
Here they describe how to display the axis numbers in binary using StrMethodFormatter
.
The code described there is:
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()
So, he is setting the y_ticks. Is there a way to display the axis in binary without setting the y ticks?
When I remove ax.yaxis.set_ticks(np.arange(0,110,10))
, then it throws the error: ValueError: Unkown format code 'b' for object of type 'float'
For my own plot all the points are integers, yet I get the same error. Does anyone know how to display the axis in binary without having to set y ticks?
Upvotes: 0
Views: 478
Reputation: 80319
Even when forcing integers via ax.yaxis.set_major_locator(MaxNLocator(integer=True))
, matplotlib still passes floats to the formatter function.
A workaround is to set a function that explicitly transforms the values to integer:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(lambda x, pos: f"{int(x):07b}")
x = np.arange(1, 10, 0.1)
ax.plot(x, x ** 2)
plt.show()
This has been tested with matplotlib 3.3.4.
For older versions, you might need a FuncFormatter
:
from matplotlib.ticker import FuncFormatter
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: f"{int(x):07b}"))
Upvotes: 1