Python 如何使用表示matplotlib中原始数据的色条绘制日志规范化imshow绘图

Python 如何使用表示matplotlib中原始数据的色条绘制日志规范化imshow绘图,python,matplotlib,normalize,Python,Matplotlib,Normalize,我使用matplotlib绘制日志规范化图像,但我希望原始原始图像数据在颜色栏中表示,而不是在[0-1]间隔中。我觉得有一种更合适的方法可以做到这一点,即使用某种规格化对象,而不是事先转换数据。。。在任何情况下,原始图像中都可能存在负值 import matplotlib.pyplot as plt import numpy as np def log_transform(im): '''returns log(image) scaled to the interval [0,1]''

我使用matplotlib绘制日志规范化图像,但我希望原始原始图像数据在颜色栏中表示,而不是在[0-1]间隔中。我觉得有一种更合适的方法可以做到这一点,即使用某种规格化对象,而不是事先转换数据。。。在任何情况下,原始图像中都可能存在负值

import matplotlib.pyplot as plt
import numpy as np

def log_transform(im):
    '''returns log(image) scaled to the interval [0,1]'''
    try:
        (min, max) = (im[im > 0].min(), im.max())
        if (max > min) and (max > 0):
            return (np.log(im.clip(min, max)) - np.log(min)) / (np.log(max) - np.log(min))
    except:
        pass
    return im

a = np.ones((100,100))
for i in range(100): a[i] = i
f = plt.figure()
ax = f.add_subplot(111)
res = ax.imshow(log_transform(a))
# the colorbar drawn shows [0-1], but I want to see [0-99]
cb = f.colorbar(res)

我尝试过使用cb.set\u数组,但似乎没有任何作用,而cb.set\u clim则完全重新缩放颜色。

是的,有!使用
LogNorm
。下面是我编写的一个实用程序的代码摘录,该实用程序用于在对数刻度上显示混淆矩阵

from pylab import figure, cm
from matplotlib.colors import LogNorm
# C = some matrix
f = figure(figsize=(6.2,5.6))
ax = f.add_axes([0.17, 0.02, 0.72, 0.79])
axcolor = f.add_axes([0.90, 0.02, 0.03, 0.79])
im = ax.matshow(C, cmap=cm.gray_r, norm=LogNorm(vmin=0.01, vmax=1))
t = [0.01, 0.1, 0.2, 0.4, 0.6, 0.8, 1.0]
f.colorbar(im, cax=axcolor, ticks=t, format='$%.2f$')
f.show()

如果您只希望对图像进行日志规范化(以增强细节),而不希望对数据进行日志规范化(以保留物理值),那么您必须对colormap本身应用转换。您可以使用烹饪书中给出的函数cmap_map()实现这一点:

显然,我可以将一个规范化实例传递到imshow中,然后图像将为我进行规范化:res=ax.imshow(im,norm=mpl.colors.LogNorm())不过,如果我附加一个颜色条,值将设置为规范化的VAL,而不是原始数据。回答得好!但是,为什么要在第二行到最后一行的格式中包含$符号呢?如果不使用,轴标签将采用sanserif字体,并与其他轴标签匹配;我可能只是从现有代码中复制并粘贴了它。我喜欢将我的情节文本延迟。这仍然是一个很好的答案!现在也存在
SymLogNorm
。它形成了一个以零为中心的对称对数标度,这可能会更好,这取决于你的数据:Laender Moesinger(上图)的评论应该是答案。它适用于负值甚至零!