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?

Schach21
  • 412
  • 4
  • 21

1 Answers1

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}"))
JohanC
  • 71,591
  • 8
  • 33
  • 66
  • 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? – Schach21 Mar 08 '21 at 01:35
  • 1
    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. – JohanC Mar 08 '21 at 01:43
  • 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? – Schach21 Mar 08 '21 at 02:49
  • I am running 3.2.2. I will update it, to see if that fixes the problem. – Schach21 Mar 08 '21 at 02:52