matplotlib中的十六进制X轴

t2a7ltrp  于 2023-03-03  发布在  其他
关注(0)|答案(3)|浏览(177)

有没有可能在matplotlib中以十六进制表示法打印X轴上的值?
在我的图中,X轴代表内存地址。

rxztt3cl

rxztt3cl1#

可以在轴上设置格式设置程序,例如FormatStrFormatter。
简单举例:

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

relj7zay2#

在64位机器上使用python3.5时,由于类型不匹配而出现错误。

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

我通过使用一个函数格式化程序来绕过它,以便能够转换为整数。

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

t1rydlwq3#

另一种方法是这样的:

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

结果:

相关问题