# Hexadecimal X-axis in matplotlib

## Question:

Is it possible to somehow have the values on the X-axis be printed in hexadecimal notation in matplotlib?

For my plot the X-axis represents memory addresses.

You can set a Formatter on the axis, for example the FormatStrFormatter.

Simple example :

``````import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

plt.plot([10, 20, 30], [1, 3, 2])
axes = plt.gca()
axes.get_xaxis().set_major_locator(ticker.MultipleLocator(1))
axes.get_xaxis().set_major_formatter(ticker.FormatStrFormatter("%x"))
plt.show()
``````

Using python 3.5 on a 64-bit machine I get errors because of a type mismatch.

``````TypeError: %x format: an integer is required, not numpy.float64
``````

I got around it by using a function formatter to be able to convert to an integer.

``````import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

def to_hex(x, pos):
return '%x' % int(x)

fmt = ticker.FuncFormatter(to_hex)

plt.plot([10, 20, 30], [1, 3, 2])
axes = plt.gca()
axes.get_xaxis().set_major_locator(ticker.MultipleLocator(1))
axes.get_xaxis().set_major_formatter(fmt)
plt.show()
``````

Another way would be this:

``````import matplotlib.pyplot as plt

# Just some 'random' data
x = sorted([489465, 49498, 5146, 4894, 64984, 465])
y = list(range(len(x)))

fig = plt.figure(figsize=(16, 4.5))
ax = fig.gca()
plt.plot(x, y, marker='o')

# Create labels
xlabels = map(lambda t: '0x%08X' % int(t), ax.get_xticks())
ax.set_xticklabels(xlabels);
``````

Result:

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.