python - 如何使用表示 matplotlib 中的原始数据的颜色条绘制对数归一化 imshow 图

标签 python matplotlib normalize

我正在使用 matplotlib 绘制对数归一化图像,但我希望原始原始图像数据在颜色栏中而不是 [0-1] 间隔中表示。我觉得有一种更 matplotlib'y 的方式来做到这一点,通过使用某种标准化对象而不是事先转换数据......在任何情况下,原始图像中可能存在负值。

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_array,但它似乎没有做任何事情,而 cb.set_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()

关于python - 如何使用表示 matplotlib 中的原始数据的颜色条绘制对数归一化 imshow 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2546475/

相关文章:

javascript - 如何使用 ajax 和 python 使 d3.js 强制定向图交互?

python - 从磁盘读取列表会比加载字典更好吗?

python-3.x - matplotlib pyplot.plot() 标记颜色

python-3.x - 升级到 2.0 后 ipython 笔记本内联 matplotlib 无法正常工作

R ggplot2直方图覆盖每个直方图的归一化值

python - pygame.Rect.move_ip() 不更新 rect 属性

Python 日志模块在 Mac 上记录,但在 Linux 上不记录

python - matplotlib 错误栏可以设置线条样式吗?

C++ Magnitude (Normalise) 似乎不正确

Pandas: Grouped DataFrame - 将列的值除以每组该列中特定行的值