如何在没有对数缩放图像的情况下应用对数轴标签(matplotlib imshow)

use*_*697 5 python numpy axes matplotlib histogram2d

我有一个大数据集,在分布上是对数的。我想做一个热图,所以我做了一个 2D 直方图并将其传递给 implot。因为数据是对数的,所以我将数据的对数传递给直方图。但是,当我绘制绘图时,我希望恢复轴(即 10^hist bin 值)和对数轴。如果我将轴设置为 log 样式,则图像看起来全部倾斜。当我将数据传递给直方图时,数据已经“记录”了,所以我不希望图像受到影响,只是轴受到影响。所以,在下面的例子中,我想要左边的图像和右边的轴。

我想我可以用一个假的叠加轴来做到这一点,但如果有更好的方法,我不喜欢做那种事情......

在此处输入图片说明

import numpy as np
import matplotlib.pyplot as plt

x=10**np.random.random(10000)*5
y=10**np.random.random(10000)*5

samps, xedges, yedges = np.histogram2d(np.log10(y), np.log10(x),     bins=50)    

ax = plt.subplot(121)

plt.imshow(samps, extent=[0,5,0,5])
plt.xlabel('Log10 X')
plt.ylabel('Log10 Y')

ax = plt.subplot(122)    
plt.imshow(samps, extent=[10**0,10**5,10**0,10**5])
plt.xlabel('X')
plt.ylabel('Y')
plt.xscale('log')
plt.yscale('log')
plt.show()
Run Code Online (Sandbox Code Playgroud)

Pau*_*l H 6

您需要使用自定义格式化程序。这是 matplotlib 文档中的一个示例:https ://matplotlib.org/examples/pylab_examples/custom_ticker1.html

我倾向于FuncFormatter像例子那样使用。主要技巧是您的函数需要接受参数xpos。老实说,我不知道这pos是为了什么。甚至可能不是故意的,但您可以将其FuncFormatter用作装饰器,这就是我在下面所做的:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

@plt.FuncFormatter
def fake_log(x, pos):
    'The two args are the value and tick position'
    return r'$10^{%d}$' % (x)

x=10**np.random.random(10000)*5
y=10**np.random.random(10000)*5

samps, xedges, yedges = np.histogram2d(np.log10(y), np.log10(x), bins=50)    

fig, (ax1) = plt.subplots()
ax1.imshow(samps, extent=[0, 5, 0, 5])
ax1.xaxis.set_major_formatter(fake_log)
ax1.yaxis.set_major_formatter(fake_log)
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明