简体   繁体   中英

Hexadecimal X-axis in matplotlib?

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.

Thanks.

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM