0

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?

1 Answer 1

1

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

example plot

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}"))
Sign up to request clarification or add additional context in comments.

4 Comments

so, doing this will "set" the y_ticks with all the integers in the array to be plotted? Meaning, if the array is [1,4,10,20] the y axis will display only the binary values for those numbers?
If you do ax.set_yticks([1,4,10,20]) both this version as well as the original StrMethodFormatter would only show these ticks as binary. Note that set_major_formatter doesn't change the positions, only the displayed tick labels. You need set_major_locator or set_yticks to change the positions.
when I run it, it produces this error: 'formatter' must be an instance of matplotlib.ticker.Formatter, not a function do you not get that error?
I am running 3.2.2. I will update it, to see if that fixes the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.